首页 > 解决方案 > 子模块如何从 lib.rs 的根目录导入特征?

问题描述

我有一个src/lib.rs包含:

pub trait Compile {
    fn from_source(src: &src) {
        parser::parse(src);
    }
}

还有一个src/compiler/interpreter.rs

use crate::Compile; // ERROR HERE - No Compile in the root

pub struct Interpreter;

impl Compile for Interpreter {}

我也有一个src/compiler.rs

pub mod interpreter;

我希望能够在我的解释器 impl 中使用 Compile 特征,但是我似乎无法弄清楚如何导入特征。有什么想法吗?

它可以src/main.rs通过这样做来做到这一点:

mod lib;
use lib::Compile;

标签: rustrust-crates

解决方案


我解决这个问题的方法是src/main.rs我使用:

use {ROOT CRATE PACKAGE NAME}::Compile;

这必须Compile纳入crate范围,所以现在我可以这样做:use crate::Compile在我的compiler子模块中。


推荐阅读