如果我有一个结构体的方法没有self
作为参数,我可以通过SomeStruct::method()
. 我似乎无法对从 trait 定义的方法做同样的事情。例如:
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
}
Run Code Online (Sandbox Code Playgroud)
编译器给出错误“unresolved name 'SomeStruct::one_trait.'”
如何直接调用 trait 方法的结构实现?
小智 5
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());
}
Run Code Online (Sandbox Code Playgroud)
来自高级特质
我相信目前这是不可能的。问题是您无法显式指定Self
类型。但有一个正在酝酿中的活跃RFC ,在实施时应该允许这样做。
与此同时,您可以像这样解决它:
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);
}
Run Code Online (Sandbox Code Playgroud)
这就是我将类型映射到整数的方法(如果这就是您想要的)。它是在没有 type 值的情况下完成的T
。虚拟值 的Static<T>
大小为零。