Search code examples
rust

How to call a trait method without a struct instance?


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?


Solution

  • 2025 edit: I would prefer to delete this outdated answer but stackoverflow does not let me do that because it has been accepted.

    I believe this is currently not possible. The problem is that you cannot explicitly specify the Self type. But there is an active RFC in the pipeline which should allow this when implemented.

    In the meantime, you could work around it like this:

    trait SomeTrait {
        fn one_trait(&self) -> uint;
    }
    
    struct Static<T>;
    
    struct SomeStruct;
    
    impl SomeTrait for Static<SomeStruct> {
        fn one_trait(&self) -> uint { 1 }
    }
    
    fn main() {
        let type_to_uint = Static::<SomeStruct>.one_trait();
        println!("{}", type_to_uint);
    }
    

    This is how I map a type to an integer (if that's what you're after). It's done without having a value of type T. The dummy value, Static<T>, has a size of zero.