在 Rust 程式設計中使用宣告


在 Rust 中,使用宣告用於將完整路徑繫結到一個新名稱。當完整路徑有點長,需要寫和呼叫時,它可能非常有用。

在正常情況下,我們習慣於做類似這樣的事情

use crate::deeply::nested::{
   my_function,
   AndATraitType
};

fn main() {
   my_function();
}

我們透過函式名稱 my_function 呼叫了 use 宣告 函式。Use 宣告 還允許我們將完整路徑繫結到我們選擇的任何新名稱。

示例

考慮以下所示示例

// Bind the `deeply::nested::function` path to `my_function`.
use deeply::nested::function as my_function;

fn function() {
   println!("called `function()`");
}

mod deeply {
   pub mod nested {
      pub fn function() {
         println!("called `deeply::nested::function()`");
      }
   }
}
fn main() {
   // Easier access to `deeply::nested::function`
   my_function();

   println!("Entering block");
   {
      // This is equivalent to `use deeply::nested::function as function`.
      // This `function()` will shadow the outer one.
      use crate::deeply::nested::function;

      // `use` bindings have a local scope. In this case, the
      // shadowing of `function()` is only in this block.
      function();
      println!("Exiting block");
   }
   function();
}

輸出

called `deeply::nested::function()`
Entering block
called `deeply::nested::function()`
Exiting block
called `function()

更新日期: 05-Apr-2021

287 次瀏覽

啟動你的 職業

透過完成本課程獲得認證

開始
廣告