描述
例子
#[derive(Debug)]
struct MyType {
name: String
}
impl MyType {
fn do_something(self, age: u32) {
//等價于 fn do_something(self: Self, age: u32) {
//等價于 fn do_something(self: MyType, age: u32) {
println!("name = {}", self.name);
println!("age = {}", age);
}
fn do_something2(&self, age: u32) {
println!("name = {}", self.name);
println!("age = {}", age);
}
}
fn main() {
let my_type = MyType{name: "linghuyichong".to_string()};
//使用self
my_type.do_something(18); //等價于MyType::do_something(my_type, 18);
//println!("my_type: {:#?}", my_type); //在do_something中,傳入的是對象,而不是引用,是以my_type的所有權就轉移到函數中了,是以不能再使用
//使用&self
let my_type2 = MyType{name: "linghuyichong".to_string()};
my_type2.do_something2(18);
my_type2.do_something2(18);
println!("my_type2: {:#?}", my_type2);//在do_something中,傳入是引用,函數并沒有擷取my_type2的所有權,是以此處可以使用
println!("Hello, world!");
}
說明