1个示例就能看明白:
//类似java里的pojo类 struct Pet{ name:String, age:i8, //最后1个,不能省略 } impl Pet{ //定义函数(类似java里的static方法) fn to_string(pet:&Pet)->String{ format!("name:{},age:{}",pet.name,pet.age) } //定义方法(类似java里的实例方法) fn to_str(&self)->String{ format!("name:{},age:{}",self.name,self.age) } } fn main() { let dog = Pet{ name:String::from("dog"), age:1 }; //调用Pet里的function println!("{}",Pet::to_string(&dog)); //调用Pet实例doc上的method println!("{}",dog.to_str()); }
输出:
name:dog,age:1
name:dog,age:1