在 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()
广告