rust - 如何正确使用与其实现分开的文件中的特征
问题描述
尝试将单独文件中定义的特征用于实现时,我有点头疼,并希望有人能指出我哪里出错了。
我的文件结构是这样的
main.rs
file1.rs
thing.rs
main.rs 的内容
mod file1;
mod thing;
fn main() {
let item : Box<dyn file1::Trait1> = Box::new(thing::Thing {});
}
文件1.rs
pub trait Trait1 {
}
东西.rs
mod file1 {
include!("file1.rs");
}
pub struct Thing {
}
impl file1::Trait1 for Thing {
}
编译时的错误是:
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`
据我所知, file1::Trait1 已实现。如果没有,我实际实施了什么?
解决方案
mod file1 {
include!("file1.rs");
}
通过将其写入thing.rs
,您创建了一个模块 ,thing::file1
它与顶级模块 不同file1
。因此,您有两个不同版本的特征,thing::file1::Trait1
并且file1::Trait1
.
这几乎从来都不是正确的事情。作为一般原则,每个.rs
文件(除了main.rs
、lib.rs
和其他 crate 根文件)都应该只有一个mod
声明。
从 中删除上述代码thing.rs
,并使用use
代替mod
,或完全限定路径:
use crate::file1;
...
impl file1::Trait1 for Thing {
...
或者
use crate::file1::Trait1;
...
impl Trait1 for Thing {
...
或者
impl crate::file1::Trait1 for Thing {
...
通常,mod
定义一个模块,并将use
项目带入范围。每个模块只写mod
一次,use
在任何你想引用该模块的地方。
推荐阅读
- c - 当在hardirq和softirq之间锁定时从另一个CPU中断时,自旋锁会死锁吗?
- reactjs - material-ui中useTheme和createMiuiTheme有什么区别
- pandas - 传递值的长度为 1,索引表示 10
- python - LinAlgError: SVD 没有收敛到 pca.fit(X_train)
- html - 与组合类相比,使用 BEM 或 ABEM 表示法有什么优势?
- javascript - 如何防止用户在输入中输入数字?
- java - 如何在 android 中测试 FusedLocationProviderClient?
- java - Java中静态嵌套类的私有成员
- java - 如何使用 RSA 将 OFB 模式添加到 3DES?
- gnome - 如何以 100% 缩放启动 evince,或其他 pdf 查看解决方案