< 返回版块

93996817 发表于 2020-08-14 23:16

看了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 !   

评论区

写评论
liangyongrui 2020-08-15 19:14

tql,先继承再扩展?

langzi.me 2020-08-15 15:36

👍

Mike Tang 2020-08-15 12:17

开眼界了。

whfuyn 2020-08-15 00:34

cool!

1 共 4 条评论, 1 页