![]() |
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:
Example 1: Rust
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. |
Reffered: https://www.geeksforgeeks.org
Rust |
Related |
---|
![]() |
![]() |
![]() |
|
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |