随着模块系统被改组为2018年版,use
关键字的功能发生了变化。什么是可以use
关键字后去有效路径?
在use
陈述路径只能启动在以下几个方面:
crate
:指自己的箱子(你的顶层)self
:指当前模块super
:指父模块范例显示了各种use
路径(Playground):
pub const NAME: &str = "peter";
pub const WEIGHT: f32 = 3.1;
mod inner {
mod child {
pub const HEIGHT: f32 = 0.3;
pub const AGE: u32 = 3;
}
// Different kinds of uses
use base64::encode; // Extern crate `base64`
use crate::NAME; // Own crate (top level module)
use self::child::AGE; // Current module
use super::WEIGHT; // Parent module (in this case, this is the same
// as `crate`)
use child::HEIGHT; // If the first name is not `crate`, `self` or
// `super` and it's not the name of an extern
// crate, it is a path relative to the current
// module (as if it started with `self`)
}
这use
陈述行为具有防锈2018改变(提供拉斯特≥1.31))。阅读this guide关于使用报表的更多信息,以及它们如何在拉斯特2018改变。
您的路径可能以两种不同的方式开始:绝对或相对的:
crate
关键字命名当前箱子开始:
struct Foo;
mod module {
use crate::Foo; // Use `Foo` from the current crate.
use serde::Serialize; // Use `Serialize` from the serde crate.
}
fn main() {}
self
,这意味着你的路径是相对于当前的模块:
mod module {
pub struct Foo;
pub struct Bar;
}
use module::Foo; // By default, you are in the `self` (current) module.
use self::module::Bar; // Explicit `self`.
在这种情况下,你可以使用super
访问到外部模块:
struct Foo;
mod module {
use super::Foo; // Access `Foo` from the outer module.
}