如何在 Rust 中使用序列号?

Eri*_*tch 0 rust

我正在寻找类似的东西(下面是C)

void MyFunction() {
    //Do work
    static int serial;
    ++serial;
    printf("Function run #%d\n", serial);
    //Do more work
}
Run Code Online (Sandbox Code Playgroud)

Frx*_*rem 7

正如Ice Giant在他们的回答中提到的,你可以用它static mut来解决这个问题。然而,它不安全是有充分理由的:如果您使用它,您有责任确保代码是线程安全的。

\n

很容易误用并在 Rust 程序中引入不健全的代码和未定义的行为,因此我建议您使用提供安全内部可变性的类型,例如 MutexRwLock、 或整数的情况,原子如AtomicU32

\n
use std::sync::atomic::{AtomicU32, Ordering};\n\nfn my_function() {\n    // NOTE: AtomicU32 has safe interior mutability, so we don\'t need `mut` here\n    static SERIAL: AtomicU32 = AtomicU32::new(0);\n\n    // fetch and increment SERIAL in a single atomic operation\n    let serial = SERIAL.fetch_add(1, Ordering::Relaxed);\n\n    // do something with `serial`...\n    println!("function run #{}", serial);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

游乐场示例

\n

由于该程序不包含任何不安全代码,因此我们可以确定该程序不包含由于 na\xc3\xafve 使用(或C 代码中的等效使用)而导致的相同数据竞争错误。static mutstatic

\n