[英]How do I correctly use traits in a file separate to its implementation
I'm having a bit of a headache trying to use traits defined in separate files to the implementation and was hoping somebody could point out where I am going wrong.我在尝试将单独文件中定义的特征用于实现时有点头疼,希望有人能指出我哪里出错了。
My file structure is this我的文件结构是这样的
main.rs
file1.rs
thing.rs
Contents of main.rs main.rs 的内容
mod file1;
mod thing;
fn main() {
let item : Box<dyn file1::Trait1> = Box::new(thing::Thing {});
}
file1.rs文件1.rs
pub trait Trait1 {
}
thing.rs东西.rs
mod file1 {
include!("file1.rs");
}
pub struct Thing {
}
impl file1::Trait1 for Thing {
}
The error on compilation is:编译的错误是:
error[E0277]: the trait bound `thing::Thing: file1::Trait1` is not satisfied
--> src/main.rs:9:41
|
9 | let item : Box<dyn file1::Trait1> = Box::new(thing::Thing {});
| ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `file1::Trait1` is not implemented for `thing::Thing`
|
= note: required for the cast to the object type `dyn file1::Trait1`
As far as I can tell file1::Trait1 is implemented.据我所知 file1::Trait1 已实现。 If not, what have I actually implemented?
如果没有,我实际实施了什么?
mod file1 {
include!("file1.rs");
}
By writing this in thing.rs
, you have created a module, thing::file1
, which is distinct from the top-level module file1
.通过在
thing.rs
编写它,您创建了一个模块thing::file1
,它不同于顶级模块file1
。 Thus, you have two distinct versions of your trait, thing::file1::Trait1
and file1::Trait1
.因此,您有两个不同版本的 trait,
thing::file1::Trait1
和file1::Trait1
。
This is almost never the right thing.这几乎从来都不是正确的事情。 As a general principle, every
.rs
file (except for main.rs
, lib.rs
, and other crate root files) should have exactly one mod
declaration .作为一般原则,每
.rs
文件(除main.rs
, lib.rs
,等箱子根文件)应该有一个确切的mod
声明。
Delete the above code from thing.rs
, and use use
instead of mod
, or a fully qualified path:从
thing.rs
删除上面的代码,并使用use
代替mod
,或者一个完全限定的路径:
use crate::file1;
...
impl file1::Trait1 for Thing {
...
or要么
use crate::file1::Trait1;
...
impl Trait1 for Thing {
...
or要么
impl crate::file1::Trait1 for Thing {
...
In general, mod
defines a module , and use
brings items into scope .通常,
mod
定义了一个 module , use
将项目引入 scope 。 You write mod
only once per module, and use
wherever you want to refer to that module.你每个模块只写一次
mod
,并在任何你想引用该模块的地方use
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.