From 1bca91ed583366ac7d7e754be576bac7be183cb5 Mon Sep 17 00:00:00 2001 From: Graham Date: Sat, 28 Sep 2024 13:26:03 +0100 Subject: [PATCH] Post on "From" trait in Rust. --- content/post/2024-09-28-ImplFrom.md | 41 +++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 content/post/2024-09-28-ImplFrom.md diff --git a/content/post/2024-09-28-ImplFrom.md b/content/post/2024-09-28-ImplFrom.md new file mode 100644 index 0000000..68d1fdd --- /dev/null +++ b/content/post/2024-09-28-ImplFrom.md @@ -0,0 +1,41 @@ +--- +title: Implement "From" Trait +subtitle: Learning Rust +date: 2024-09-28 +tags: [ + "programming", + "code", + "rust", +] +--- + +# Implement "From" trait... + +Basic implementation of From trait to create "MyStruct" from +``` +struct MyStruct{ + word: String, + number: i32 +} + +impl From for MyStruct{ + fn from(num: i32) -> MyStruct { + MyStruct { + word: "notset".to_string(), + number: num + } + } + +} + +fn main() { + let m = MyStruct::from(25); + println!("Struct made: word={}, number={}.", m.word, m.number); +} +``` + +## Output of above: + +``` +Struct made: word=notset, number=25. +```