RosettaCodeData/Task/Call-an-object-method/Rust/call-an-object-method.rust

32 lines
1.0 KiB
Plaintext

struct Foo;
impl Foo {
// implementation of an instance method for struct Foo
// returning the answer to life
fn get_the_answer_to_life(&self) -> i32 {
42
}
// implementation of a static method for struct Foo
// returning a new instance object
fn new() -> Foo {
println!("Hello, world!");
Foo // returning the new Foo object
}
}
fn main() {
// create the instance object foo,
// by calling the static method new of struct Foo
let foo = Foo::new();
// get the answer to life
// by calling the instance method of object foo
println!("The answer to life is {}.", foo.get_the_answer_to_life());
// Note that in Rust, methods still work on references to the object.
// Rust will automatically do the appropriate dereferencing to get the method to work:
let lots_of_references = &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&foo;
println!("The answer to life is still {}." lots_of_references.get_the_answer_to_life());
}