DEV Community

Zhangwuji
Zhangwuji

Posted on

rust trait

you can regard trait as interface as ts.but it is more flexiable.

pub struct Animal {
   name:String
}
pub trait Action {
    fn say() ;
    fn getName -> String;
}
impl  Action for Animal {
     fn say(){

      },
    fn getName() ->String{

    } 
}
Enter fullscreen mode Exit fullscreen mode

and you can set default implement for tait
such as

pub trait Action {
   fn say(){

      },
    fn getName -> String;
}

impl  Action for Animal {

    fn getName() ->String{

    } 
}

Enter fullscreen mode Exit fullscreen mode

seond powerful function

pub trait Action<T,U> {
   fn say(){

      },
    fn getName -> String;
}

pub trait2 Action<T,U> {
   fn say(){

      },
    fn getName -> String;
}

fn main(ff:impl trait<String,String> + trait2<String,String> ) {

}

fn main<T:trait<String,String> + trait2<String,String>>(ff:T){

}

fn main<T,U>(ff:T)
where
   T:trait<String,String> + trait2<String,String>
{

}
Enter fullscreen mode Exit fullscreen mode

the three methods are equal

Top comments (0)