Super 和 Self

RustRustBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将探索 Rust 中 superself 关键字的用法,以消除访问项时的歧义并避免硬编码路径。

注意:如果实验未指定文件名,你可以使用任何你想要的文件名。例如,你可以使用 main.rs,并通过 rustc main.rs &&./main 进行编译和运行。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("Rust")) -.-> rust/DataTypesGroup(["Data Types"]) rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust(("Rust")) -.-> rust/MemorySafetyandManagementGroup(["Memory Safety and Management"]) rust(("Rust")) -.-> rust/DataStructuresandEnumsGroup(["Data Structures and Enums"]) rust/DataTypesGroup -.-> rust/type_casting("Type Conversion and Casting") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("Lifetime Specifiers") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("Method Syntax") subgraph Lab Skills rust/type_casting -.-> lab-99335{{"Super 和 Self"}} rust/function_syntax -.-> lab-99335{{"Super 和 Self"}} rust/expressions_statements -.-> lab-99335{{"Super 和 Self"}} rust/lifetime_specifiers -.-> lab-99335{{"Super 和 Self"}} rust/method_syntax -.-> lab-99335{{"Super 和 Self"}} end

superself

superself 关键字可用于路径中,以消除访问项时的歧义,并防止路径出现不必要的硬编码。

fn function() {
    println!("called `function()`");
}

mod cool {
    pub fn function() {
        println!("called `cool::function()`");
    }
}

mod my {
    fn function() {
        println!("called `my::function()`");
    }

    mod cool {
        pub fn function() {
            println!("called `my::cool::function()`");
        }
    }

    pub fn indirect_call() {
        // 让我们从这个作用域中访问所有名为 `function` 的函数!
        print!("called `my::indirect_call()`, that\n> ");

        // `self` 关键字指代当前模块作用域——在这种情况下是 `my`。
        // 调用 `self::function()` 和直接调用 `function()` 都会得到
        // 相同的结果,因为它们指代同一个函数。
        self::function();
        function();

        // 我们也可以使用 `self` 来访问 `my` 内部的另一个模块:
        self::cool::function();

        // `super` 关键字指代父作用域(在 `my` 模块之外)。
        super::function();

        // 这将绑定到 *包* 作用域中的 `cool::function`。
        // 在这种情况下,包作用域是最外层作用域。
        {
            use crate::cool::function as root_function;
            root_function();
        }
    }
}

fn main() {
    my::indirect_call();
}

总结

恭喜你!你已经完成了“Super”和“Self”实验。你可以在 LabEx 中练习更多实验来提升你的技能。