Open In App

Rust – The newtype Idiom

Last Updated : 18 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, we have a concept of “newtype idiom” that is categorized under Rust generics. The newtype idiom is a design pattern in Rust that is responsible for ensuring safe coding practices and also ensures that our code is type-safe. The main function of newtype idiom is ensuring that the right value type is provided to the program at compile time.

The newtype patterns are used in scenarios of primitive type like number or string and they are wrapped inside a struct so that when the programmer debugs the code then the type checker in Rust could catch any type of errors and provide safety to our code and at the same time enhance our code readability.

Syntax:

impl GFG 

 {
   
   pub fn new

(
       // pub refers to the function being declared public
   ) -Self 

{

——–

——–

}

}

Example 1:

Rust




# Rust program for newtype idiom
pub struct Year(String);
impl Year {
    pub fn new(y: String) -> Year {
        Year(y)
    }
    pub fn string_fun(&self) -> &str {
        &self.0
    }
}
  
fn main() {
    let num = Year::new("2022".to_string());
    println!("Technical Scripter Event {}", num.string_fun())
}


Output:

 

Explanation:

In this example, we have declared a struct GFG and made it public using ‘pub’. Next, we declare an impl Year and pass a string to it. The newtype idiom is public (pub) in nature and its internal data components are private. The inner field is declared as 0 and all the code logic is wrapped around the data. 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads