(done) 速通 rustlings(7) 全局变量/常量

RUST 中,let 不能用于声明全局变量

全局常量必须显示声明类型

rust 复制代码
// The type of constants must always be annotated.
const NUMBER: u64 = 3;

fn main() {
    println!("Number: {NUMBER}");
}

另一种全局 "常量" 声明方式是使用 static,默认只读。

若使用 static mut,则是可变全局变量,由于可变全局变量容易造成别名/并发问题,必须使用 unsafe 块访问。

rust 复制代码
static GREETING: &str = "hello";       // 只读全局
static mut COUNTER: i32 = 0;           // 可变全局,需要 unsafe

fn incr() {
    unsafe {
        COUNTER += 1;                  // 修改时要显式不安全
    }
}

fn main() {
    println!("{GREETING}");
    unsafe { println!("count = {COUNTER}"); }
    incr();
}

使用 static 声明的全局常量和使用 const 声明的全局常量区别如下:

相关推荐
敲敲了个代码2 小时前
构建工具的第三次革命:从 Rollup 到 Rust Bundler,我是如何设计 robuild 的
开发语言·前端·javascript·后端·rust
lpfasd1232 小时前
Tauri 中实现自更新(Auto Update)
rust·tauri·update
shimly1234562 小时前
(done) 速通 rustlings(10) 基本数据类型
rust
shimly1234562 小时前
(done) 速通 rustlings(8) 函数
rust
busideyang3 小时前
MATLAB vs Rust在嵌入式领域的角色定位
开发语言·matlab·rust
Source.Liu4 小时前
【a11】项目命名笔记:`a11` (合一)
rust·egui
Source.Liu18 小时前
【egui】官方示例 hello_world 完全解析
rust·egui
CS生1 天前
Rust环境准备
开发语言·后端·rust
沛沛rh451 天前
Rust 中的三个“写手“:print!、format!、write! 的详细区别
开发语言·后端·rust