在 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()
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP