Implement “From” trait…
Basic implementation of From trait to create “MyStruct” from type: i32
struct MyStruct{
word: String,
number: i32
}
impl From<i32> for MyStruct{
fn from(num: i32) -> MyStruct {
MyStruct {
word: "notset".to_string(),
number: num
}
}
}
fn main() {
let m = MyStruct::from(25);
let n: MyStruct = 30.into();
println!("Struct m: word={}, number={}.", m.word, m.number);
println!("Struct n: word={}, number={}.", n.word, n.number);
}
Notice that I can run 30.into
above. I didn’t add that explicitly.
Output of above:
Struct m: word=notset, number=25.
Struct n: word=notset, number=30.