Skip to content

Instantly share code, notes, and snippets.

@ejangi
Created May 29, 2024 00:54
Show Gist options
  • Save ejangi/e315491bd855158cd0fac2f39d95f4b2 to your computer and use it in GitHub Desktop.
Save ejangi/e315491bd855158cd0fac2f39d95f4b2 to your computer and use it in GitHub Desktop.
// Define a struct called Person
struct Person {
name: String,
age: u8,
}
impl Person {
// Method to create a new person
fn new(name: &str, age: u8) -> Person {
Person {
name: name.to_string(),
age,
}
}
// Method to modify the age of a person
fn grow_up(&mut self) {
self.age += 1;
}
// Method to print out information about a person
fn describe(&self) {
println!("Name: {}, Age: {}", self.name, self.age);
}
}
fn main() {
// Create a new person
let mut john = Person::new("John", 30);
// Print out the initial state of John
john.describe();
// Make John grow up
john.grow_up();
// Print out the updated state of John
john.describe();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment