Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a trait method without a struct instance?

Tags:

rust

If I have a struct with a method that doesn't have self as an argument, I can call the method via SomeStruct::method(). I can't seem to do the same with a method that's defined from a trait. For example:

trait SomeTrait {
    fn one_trait() -> uint;
}

struct SomeStruct;
impl SomeStruct {
    fn one_notrait() -> uint {
        1u
    }
}
impl SomeTrait for SomeStruct {
    fn one_trait() -> uint {
        1u
    }
}

#[test]
fn testing() {
    SomeStruct::one_trait();   // doesn't compile
    SomeStruct::one_notrait(); // compiles
}

The compiler gives the error "unresolved name 'SomeStruct::one_trait.'"

How can I call a struct's implementation of a trait method directly?

like image 820
awelkie Avatar asked Dec 25 '22 05:12

awelkie


1 Answers

trait Animal {
    fn baby_name() -> String;
}

struct Dog;

impl Dog {
    fn baby_name() -> String {
        String::from("Spot")
    }
}

impl Animal for Dog {
    fn baby_name() -> String {
        String::from("puppy")
    }
}

fn main() {
    println!("A baby dog is called a {}", <Dog as Animal>::baby_name());
}

From Advanced Trait

like image 123
clearloop Avatar answered Dec 31 '22 01:12

clearloop