Implement "From" Trait

Learning Rust

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. [Read More]

Rust "Classes" -> struct + impl

Learning Rust

Q: How do I write a class in Rust? A: Use a struct and “impl” some functions. struct MyStruct{ word: String, number: i32 } impl MyStruct{ pub fn new(s: String, i: i32) -> MyStruct { return MyStruct{ word: s, number: i } } pub fn set_word(&mut self, w: String) { self.word = w; } pub fn set_number(&mut self, n: i32) { self.number = n; } pub fn word(&self) -> String { self. [Read More]

Rust Traits

Learning Rust

Rust Traits, what are they? This concept is interesting and I wanted to write it down as I learned it. I’ve just started learing Rust and will have the terminology wrong! Traits can be added to types to allow them to do something, as if these were classes in C++ that already had methods implemented. In this scenario, I’m imagining that it’s very importand to check if a number is divisible by seven, and if it actually is the number seven. [Read More]