Rust 有問有答之 use 關鍵字

use 是什麼

use 是 Rust 編程語言的關鍵字。using 是 編程語言 C# 的關鍵字。

關鍵字是預定義的保留標識符,對編譯器有特殊意義。

using 關鍵字有三個主要用途:

  • using 語句定義一個範圍,在此範圍的末尾將釋放對象。

  • using 指令爲命名空間創建別名,或導入在其他命名空間中定義的類型。

  • using static 指令導入單個類的成員。

use的用途是什麼

類比using,use的用途有:

  • 用於引用某個外部模塊
  • 直接使用枚舉值,而無需手動加上作用域
  • 爲某個作用域下的方法或作用域創建別名

用於引用某個外部模塊

外部模塊 a.rs,代碼內容如下

mod a
{
	fn print_function()
	{
		println!("This is a.print_function.");
	}
}

主函數 main.rs 想要調用 print_function,需要對 mod 標識訪問級別,使用關鍵字 pub。所以 a.rs 的內容變動如下

pub mod a
{
	fn print_function()
	{
		println!("This is a.print_function.");
	}
}

主函數 main.rs 調用 print_function 如下,使用關鍵字 use:

use a;

fn main()
{
	a::print_function();
}

直接使用枚舉值,而無需手動加上作用域

enum Status {
    Rich,
    Poor,
}

fn main()
{
    use Status::{Poor, Rich};
    let status = Poor;
}

上述代碼使用關鍵字 use 顯示聲明瞭枚舉 Status,所以在 let status = Poor; 這行代碼中無需使用 Status::Poor 手動加上作用域的方式聲明 Poor

當然如果枚舉值過多時,可以使用 * 聲明所有枚舉值,即 use Status::*;

爲某個作用域下的方法或作用域創建別名

pub mod a 
{
    pub mod b
    {
        pub fn function()
        {
            println!("This is a::b::function");
        }

        pub fn other_funtion()
        {
            println!("This is a::b::other_funtion");
        }
    }
}

use a::b as ab;
use a::b::other_funtion as ab_funtion;

fn main()
{
    ab::function();
    ab::other_funtion();
    ab_funtion();
}

如上述例子所示

use a::b as ab;使用關鍵字 use 爲作用域創建別名。

use a::b::other_funtion as ab_funtion; 爲方法 other_funtion 創建別名 ab_funtion 。

參考:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章