Rust 变量绑定声明

RustRustBeginner
立即练习

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

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

简介

在本实验中,我们将看到一个在 Rust 编程语言中先声明变量绑定,然后再进行初始化的示例。

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust(("Rust")) -.-> rust/BasicConceptsGroup(["Basic Concepts"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("Variable Declarations") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") subgraph Lab Skills rust/variable_declarations -.-> lab-99293{{"Rust 变量绑定声明"}} rust/function_syntax -.-> lab-99293{{"Rust 变量绑定声明"}} rust/expressions_statements -.-> lab-99293{{"Rust 变量绑定声明"}} end

先声明

可以先声明变量绑定,之后再对其进行初始化。不过,这种形式很少使用,因为它可能会导致使用未初始化的变量。

fn main() {
    // 声明一个变量绑定
    let a_binding;

    {
        let x = 2;

        // 初始化该绑定
        a_binding = x * x;
    }

    println!("a binding: {}", a_binding);

    let another_binding;

    // 错误!使用了未初始化的绑定
    println!("another binding: {}", another_binding);
    // FIXME ^ 注释掉这一行

    another_binding = 1;

    println!("another binding: {}", another_binding);
}

编译器禁止使用未初始化的变量,因为这会导致未定义行为。

总结

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