【发布时间】:2019-03-25 07:28:25
【问题描述】:
我在 Rust 中有以下代码:
trait MyTrait {
fn get_value() -> &'static str;
}
#[derive(Debug)]
struct MyStruct;
impl MyTrait for MyStruct {
fn get_value() -> &'static str {
"has value"
}
}
fn main() {
println!("My value: {}", MyStruct::get_value());
has_trait(MyStruct);
}
fn has_trait<T>(trt: T) where T: MyTrait + std::fmt::Debug {
println!("{:?}", trt)
}
这段代码很好。它定义了一个特征和一个结构。该结构实现了特征;这需要实现一个功能。到目前为止一切都很好。但如果我尝试以下代码:
trait MyTrait {
fn get_value() -> &'static str;
}
#[derive(Debug)]
struct MyStruct;
impl MyTrait for MyStruct {
fn get_value() -> &'static str {
"has value"
}
}
fn main() {
println!("My value: {}", MyStruct::get_value());
has_trait(MyStruct);
}
fn has_trait<T>(trt: T) where T: MyTrait + std::fmt::Debug {
println!("{:?}", trt::get_value())
}
我收到以下错误:
error[E0433]: failed to resolve: use of undeclared type or module `trt`
--> src/main.rs:21:22
|
21 | println!("{:?}", trt::get_value())
| ^^^ use of undeclared type or module `trt`
现在,我不太明白为什么这行不通。 trt 应该代表myStruct 的一个副本,然后它应该有自己的功能,对吧?
有趣的是,以下代码将编译:
trait MyTrait {
fn get_value(&self) -> &'static str;
}
#[derive(Debug)]
struct MyStruct;
impl MyTrait for MyStruct {
fn get_value(&self) -> &'static str {
"has value"
}
}
fn main() {
println!("My value: {}", MyStruct.get_value());
has_trait(MyStruct);
}
fn has_trait<T>(trt: T) where T: MyTrait + std::fmt::Debug {
println!("{:?}", trt.get_value())
}
那么无法编译的代码到底有什么问题呢?
【问题讨论】:
标签: rust