Rust 编程中的 Super 和 Self 关键字
当我们想移除从同一函数或其他模块调用的函数的繁琐的冗长导入路径时,我们可以使用 Rust 中提供的 super 和 self 关键字。
当我们想访问项时,这些关键字有助于消除歧义,还可以防止不必要的路径硬编码。
示例
考虑下面显示的一个简单示例
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()`
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP