Skip to content

Instantly share code, notes, and snippets.

@EteimZ
Created April 1, 2023 19:44
Show Gist options
  • Select an option

  • Save EteimZ/3385754a192c6362dd009268e5ddc415 to your computer and use it in GitHub Desktop.

Select an option

Save EteimZ/3385754a192c6362dd009268e5ddc415 to your computer and use it in GitHub Desktop.
Introduction to structs in rust
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