rust / intermediate
Snippet
From and Into Trait Pairs
From and Into are complementary traits that enable flexible type conversions. When you implement From for your type, Into is automatically implemented. This follows the principle that conversions should be obvious rather than implicit.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#[derive(Debug)]struct Person {name: String,age: u32,}impl From<(String, u32)> for Person {fn from(tuple: (String, u32)) -> Self {Person { name: tuple.0, age: tuple.1 }}}impl From<&str> for Person {fn from(s: &str) -> Self {let parts: Vec<&str> = s.split(',').collect();Person {name: parts[0].to_string(),age: parts[1].trim().parse().unwrap_or(0),}}}fn main() {let p1: Person = (String::from("Alice"), 30).into();let p2: Person = Person::from("Bob,25");println!("{:?} and {:?}", p1, p2);}
Breakdown
1
impl From<(String, u32)> for Person
Implements From for a tuple of name and age
2
fn from(tuple: (String, u32)) -> Self
Takes ownership of the tuple and creates Person
3
impl From<&str> for Person
Also implements From for string slice parsing
4
let p1: Person = (String::from("Alice"), 30).into();
Into is called via method syntax on the tuple
5
let p2: Person = Person::from("Bob,25");
Can also use From directly with explicit type