rust通过泛型给结构体添加方法,示例
trait IUser {
fn set_name(&mut self, name: &str);
}
trait GUser: IUser {
fn gen_name(&mut self) {
self.set_name("default");
}
}
struct User {
name: String,
}
impl IUser for User {
fn set_name(&mut self, name: &str) {
self.name = String::from(name)
}
}
impl<R: IUser + ?Sized> GUser for R {}
fn main() {
let mut u = User { name: "".to_string() };
u.gen_name();
}