Answers for "rust structs and methods on simple object"

2

rust structs and methods on simple object

struct Person {
    name:String,
}

impl Person {
    fn new(name:&str) -> Self {Person{name:name.to_string()}}
    pub fn greet(self: &Self, name: &str) -> String {
        format!("Hello {}, my name is {}.", name, self.name)
    }
}

fn main() {
    // define variable based on struct
    let p1 = Person::new("Able");
    println!("{}", p1.name);  // "Able"
    // use a method connected to struct
    println!("{}", p1.greet("Baker"));   // "Hello Baker, my name is Able");
}
Posted by: Guest on March-08-2021

Browse Popular Code Answers by Language