看了Bevy的示例:Rust还可以这样写
pub fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {
type_name::<T>()
}
fn hello_world() {
println!("hello world!");
}
fn test2(){
println!("test2 method");
}
trait AddMethod:std::ops::FnMut(){
fn exec(&mut self){
println!("start {} !",type_name_of_val(self));
self();
println!("end {} !",type_name_of_val(self));
}
}
impl<T> AddMethod for T where T:FnMut(){}
fn main() {
hello_world.exec(); // trait extension method
test2.exec();
}
结果
start test001::hello_world !
hello world!
end test001::hello_world !
start test001::test2 !
test2 method
end test001::test2 !
1
共 4 条评论, 1 页
评论区
写评论tql,先继承再扩展?
👍
开眼界了。
cool!