Created
April 1, 2023 19:44
-
-
Save EteimZ/3385754a192c6362dd009268e5ddc415 to your computer and use it in GitHub Desktop.
Introduction to structs in rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| struct Person{ | |
| name: String, | |
| age: u32, | |
| } | |
| impl Person{ | |
| fn intro(&self){ | |
| println!("My name is {0} and I am {1} years old", self.name, self.age ); | |
| } | |
| fn age(&self)->u32{ | |
| self.age | |
| } | |
| fn set_age(&mut self, new_age: u32){ | |
| self.age = new_age; | |
| } | |
| } | |
| fn main() { | |
| let mut p = Person{ | |
| name: String::from("Eteims"), | |
| age:23 | |
| }; | |
| // introduce person | |
| p.intro(); | |
| // get person's age | |
| let my_age = p.age(); | |
| println!("age: {my_age}"); | |
| // update person's age | |
| p.set_age(43); | |
| println!("new age: {}", p.age()); | |
| } | |
| /* output: | |
| My name is Eteims and I am 23 years old | |
| age: 23 | |
| new age: 43 | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment