Rust 程式設計中的 Super 和 Self 關鍵字


當我們想移除從同一函式或其他模組呼叫的函式的繁瑣的冗長匯入路徑時,我們可以使用 Rust 中提供的 superself 關鍵字。

當我們想訪問項時,這些關鍵字有助於消除歧義,還可以防止不必要的路徑硬編碼。

示例

考慮下面顯示的一個簡單示例

fn function() {
   println!("called `function()`");
}
mod cool {
   pub fn function() {
      println!("called `cool::function()`");
   }
}
mod my {
   fn function() {
      println!("called `my::function()`");
   }
   mod cool {
      ub fn function() {
         println!("called `my::cool::function()`");
      }
   }

   pub fn my_call() {
      // Let's access all the functions named `function` from this scope!
      print!("called `my::my_call()`, that
> ");       self::function();       function();       // We can also use `self` to access another module inside `my`:       self::cool::function();       super::function(); // This will bind to the `cool::function` in the *crate* scope. // In this case the crate scope is the outermost scope. {     use crate::cool::function as root_function;     root_function(); } } } fn main() { my::my_call(); }

當我們使用 self 關鍵字時,它引用當前模組作用域,因此,呼叫 self::function()function() 沒有區別。

當我們在呼叫函式前加上 super 關鍵字時,我們嘗試引用父作用域(或另一個模組)。

輸出

called `my::my_call()`, that
> called `my::function()`
called `my::function()`
called `my::cool::function()`
called `function()`
called `cool::function()`

更於:2021-04-05

525 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告