Skip to main content

Trait

  • Traits are interfaces with extension feature in swift. trait can be implement by existing type but interfaces can't.
trait Hash {
fn hash(&self) -> u64;
}

impl Hash for bool {
fn hash(&self) -> u64 {
if *self { 0 } else { 1 }
}
}

fn test() {
println!("{}", true.hash());
}
  • Trait bound to generics.
pub fn notify(item: &impl Summary) {
println!("Breaking news! {}", item.summarize());
}

pub fn notify<T: Summary>(item: &T) {
println!("Breaking news! {}", item.summarize());
}

pub fn notify(item: &(impl Summary + Display)) {}

pub fn notify<T: Summary + Display>(item: &T) {}

pub fn notify<T>(item: &T)
where T: Summary + Display {}