rust trait

zhangwuji

Zhangwuji

Posted on May 22, 2024

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

💖 💪 🙅 🚩
zhangwuji
Zhangwuji

Posted on May 22, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related