代码之家  ›  专栏  ›  技术社区  ›  Boiethios

use关键字中的有效路径根是什么?

  •  1
  • Boiethios  · 技术社区  · 6 年前

    随着2018年版模块系统的更新,系统的功能 use 关键字已更改。哪些有效路径可以在 使用 关键字?

    2 回复  |  直到 6 年前
        1
  •  3
  •   Shepmaster Tim Diekmann    6 年前

    路径在 use 语句只能以以下方式开始:

    • 外部板条箱的名称 :那么它指的是外部板条箱
    • crate :指您自己的板条箱(顶层)。
    • self :指当前模块
    • super :指父模块
    • 别名 :在这种情况下,它会查找该名称 相对的 到当前模块

    一个演示各种 使用 -路径( 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`)
    }
    

    这个 使用 声明行为随Rust 2018而变化(Rust_1.31中提供)。读 this guide 更多关于2018年Rust使用声明及其变化的信息。

        2
  •  1
  •   Boiethios    6 年前

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

    • 您的路径可以以板条箱名称开始,或者 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.
      }