什么是使用关键字的有效途径根源是什么?

问题描述 投票:2回答:2

随着模块系统被改组为2018年版,use关键字的功能发生了变化。什么是可以use关键字后去有效路径?

module rust rust-2018
2个回答
4
投票

use陈述路径只能启动在以下几个方面:

  • 一个外部箱的名称。然后它指的extern箱
  • 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改变。


2
投票

您的路径可能以两种不同的方式开始:绝对或相对的:

  • 你的路径可以用一个箱子的名称,或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. }
© www.soinside.com 2019 - 2024. All rights reserved.