define struct method rust code example
Example: 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");
}