use 是什么
use 是 Rust 編程語言的關(guān)鍵字。using 是 編程語言 C# 的關(guān)鍵字。
關(guān)鍵字是預(yù)定義的保留標(biāo)識符,對編譯器有特殊意義。
using關(guān)鍵字有三個主要用途:
using 語句定義一個范圍,在此范圍的末尾將釋放對象。
using 指令為命名空間創(chuàng)建別名,或?qū)朐谄渌臻g中定義的類型。
using static 指令導(dǎo)入單個類的成員。
use的用途是什么
類比using,use的用途有:
- 用于引用某個外部模塊
- 直接使用枚舉值,而無需手動加上作用域
- 為某個作用域下的方法或作用域創(chuàng)建別名
用于引用某個外部模塊
外部模塊 a.rs,代碼內(nèi)容如下
mod a
{
fn print_function()
{
println!("This is a.print_function.");
}
}
主函數(shù) main.rs 想要調(diào)用 print_function,需要對 mod 標(biāo)識訪問級別,使用關(guān)鍵字 pub。所以 a.rs 的內(nèi)容變動如下
pub mod a
{
fn print_function()
{
println!("This is a.print_function.");
}
}
主函數(shù) main.rs 調(diào)用 print_function 如下,使用關(guān)鍵字 use:
use a;
fn main()
{
a::print_function();
}
直接使用枚舉值,而無需手動加上作用域
enum Status {
Rich,
Poor,
}
fn main()
{
use Status::{Poor, Rich};
let status = Poor;
}
上述代碼使用關(guān)鍵字 use 顯示聲明了枚舉 Status,所以在 let status = Poor; 這行代碼中無需使用 Status::Poor 手動加上作用域的方式聲明 Poor。
當(dāng)然如果枚舉值過多時,可以使用 * 聲明所有枚舉值,即 use Status::*; 。
為某個作用域下的方法或作用域創(chuàng)建別名
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;使用關(guān)鍵字 use 為作用域創(chuàng)建別名。
use a::b::other_funtion as ab_funtion; 為方法 other_funtion 創(chuàng)建別名 ab_funtion 。
參考: