如题,通过impl构造多个函数,实现链式调用。
#[derive(Debug)]
pub struct Animal{
name:String,
age:i32
}
impl Animal{
pub fn new() ->Self{
Animal{name:"dog".to_string(),age:2}
}
pub fn setname(mut self,name:String)->Self{
self.name = name;
self
}
pub fn setage(mut self,age:i32)->Self{
self.age = age;
self
}
pub fn build(self)->Animal{
Animal{
name:self.name.clone(),
age:self.age
}
}
}
fn main(){
let car=Animal::new()
.setname("apple".to_string())
.setage(6)
.build();
println!("{:?}",car);
}