简体   繁体   English

rust 来自 main.rs 的模块解析

[英]rust modules resolution from main.rs

I have a question about rust modules resolution.我有一个关于 rust 模块分辨率的问题。 It seems to be that inside crate modules I can reference the other modules using crate name or crate / super / self keywords.似乎在板条箱模块内部,我可以使用板条箱名称或crate / super / self关键字引用其他模块。 but in main.rs I can only use modules with crate name?但是在main.rs中我只能使用带有板条箱名称的模块?

Am I doing something stupid here?我在这里做傻事吗?

My project:我的项目:

$ tree
.
├── Cargo.toml
└── src
    ├── add2.rs
    ├── add.rs
    ├── lib.rs
    └── main.rs

Cargo.toml content: Cargo.toml内容:

[package]
name = "example"
....

main.rs content: main.rs内容:

use example::add::{add_one};
fn main() {
    println!("{}", add_one(1));
}

lib.rs content: lib.rs内容:

pub mod add;

add.rs content: add.rs内容:

pub fn add_one(x: i32) -> i32 {
    x + 1
}

add2.rs content: add2.rs内容:

use crate::add::{add_one};

pub fn add_two(x: i32) -> i32 {
    add_one(add_one(x))
}

Am I doing something stupid here?我在这里做傻事吗?

No, it`s just that Cargo adds one more layer of complexity called the "package", for better or worse, which makes it more confusing.不,只是 Cargo 增加了一层称为“包”的复杂性,无论好坏,这使得它更加混乱。

In short, your Cargo package contains two Rust crates: the binary one and the library one.简而言之,您的 Cargo package 包含两个 Rust 箱:二进制箱和库箱。 When you are in main.rs , the example library crate is an external dependency like any other... which means you aren`t in the same crate!当您在main.rs中时, example库 crate 与任何其他库一样是外部依赖项……这意味着您不在同一个 crate 中!

Crate roots such as main.rs , lib.rs , bin/other_root.rs , etc. are treated differently by the module system.模块系统对 main.rs 、 main.rsbin/other_root.rs lib.rs板条箱根进行不同的处理。 When they refer to module files they are referring to files in the root of the src/ directory only.当它们引用模块文件时,它们仅指src/目录根目录中的文件。 In the normal case mod refers to files in the root of a local sub-directory with the same name as the containing file, mirroring the unique container constraint of the inline module layout as well as the file system hierarchy (barring linked files, of course).在正常情况下, mod指的是本地子目录根目录中与包含文件同名的文件,反映了内联模块布局的唯一容器约束以及文件系统层次结构(当然,除了链接文件). In essence, crate roots treat src/ as their local sub-directory as far as mod is concerned.本质上,就mod而言,crate roots 将src/视为它们的本地子目录。

I gave perhaps a more wordy explanation here我在这里可能给出了更冗长的解释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM