rust / intermediate
Snippet
Tuple Structs for Newtype Pattern
Tuple structs (also called newtype patterns) wrap a single value in a struct with named fields accessed by index (.0, .1, etc.). They provide type safety by creating distinct types that prevent mixing up parameters of the same underlying type, such as UserId versus Username both containing Strings.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct UserId(u64);struct Username(String);struct Email(String);fn main() {let id = UserId(42);let name = Username(String::from("alice"));println!("User {} has email {}", name.0, email.0);let doubled = UserId(id.0 * 2);println!("Doubled ID: {}", doubled.0);}
Breakdown
1
struct UserId(u64)
Newtype wrapper around u64 representing a user identifier
2
struct Username(String)
Newtype wrapper around String for username storage
3
struct Email(String)
Newtype wrapper around String for email address storage
4
let id = UserId(42)
Create a UserId instance containing the value 42
5
println!("User {} has email {}", name.0, email.0)
Access the inner String values using .0 index notation
6
let doubled = UserId(id.0 * 2)
Perform operations on the inner value and wrap result in new UserId