How to call a trait method without a struct instan

2019-07-16 17:49发布

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?

标签: rust
1条回答
女痞
2楼-- · 2019-07-16 18:24

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.

查看更多
登录 后发表回答