探索 Rust 常量

RustRustBeginner
立即练习

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

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

简介

在本实验中,我们将介绍Rust中常量的概念,常量可以使用 conststatic 关键字声明,并带有显式类型注释,且可以在任何作用域(包括全局作用域)中访问。

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("Rust")) -.-> rust/BasicConceptsGroup(["Basic Concepts"]) rust(("Rust")) -.-> rust/DataTypesGroup(["Data Types"]) rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("Variable Declarations") rust/BasicConceptsGroup -.-> rust/constants_usage("Constants Usage") rust/DataTypesGroup -.-> rust/integer_types("Integer Types") rust/DataTypesGroup -.-> rust/string_type("String Type") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") subgraph Lab Skills rust/variable_declarations -.-> lab-99275{{"探索 Rust 常量"}} rust/constants_usage -.-> lab-99275{{"探索 Rust 常量"}} rust/integer_types -.-> lab-99275{{"探索 Rust 常量"}} rust/string_type -.-> lab-99275{{"探索 Rust 常量"}} rust/function_syntax -.-> lab-99275{{"探索 Rust 常量"}} rust/expressions_statements -.-> lab-99275{{"探索 Rust 常量"}} end

常量

Rust 有两种不同类型的常量,它们可以在包括全局作用域在内的任何作用域中声明。两者都需要显式的类型注释:

  • const:一个不可变的值(常见情况)。
  • static:一个可能可变的具有 'static 生命周期的变量。静态生命周期是推断出来的,不必指定。访问或修改可变的静态变量是 unsafe 的。
// 全局变量在所有其他作用域之外声明。
static LANGUAGE: &str = "Rust";
const THRESHOLD: i32 = 10;

fn is_big(n: i32) -> bool {
    // 在某个函数中访问常量
    n > THRESHOLD
}

fn main() {
    let n = 16;

    // 在主线程中访问常量
    println!("This is {}", LANGUAGE);
    println!("The threshold is {}", THRESHOLD);
    println!("{} is {}", n, if is_big(n) { "big" } else { "small" });

    // 错误!不能修改 `const`。
    THRESHOLD = 5;
    // FIXME ^ 注释掉这一行
}

总结

恭喜你!你已经完成了常量实验。你可以在LabEx中练习更多实验来提升你的技能。