rust - 如何在Rust中为返回的元组设置静态生存期?

标签 rust lifetime memory-safety

假设我有以下返回元组的构造函数:

pub struct WebCam {
    id: u8
}

impl WebCam {
    fn new() -> (Self, bool) {
        let w = WebCam {id: 1 as u8};
        return (w, false);
    }
}

pub fn main() {
    static (cam, isRunning): (WebCam, bool) = WebCam::new();
}

上面的代码无法编译。但是,如果我将static更改为let,则可以正常编译。我不确定如何在返回的元组的单个值上设置生命周期(一行)?

最佳答案

https://doc.rust-lang.org/reference/items/static-items.html

是否应该使用常量项目还是静态项目可能会造成混淆。通常,常量应优先于静态,除非满足以下条件之一:

正在存储大量数据
静态变量的单地址属性是必需的。
内部可变性是必需的。

A static item is similar to a constant, except that it represents a precise memory location in the program. All references to the static refer to the same memory location. Static items have the static lifetime, which outlives all other lifetimes in a Rust program. Non-mut static items that contain a type that is not interior mutable may be placed in read-only memory. Static items do not call drop at the end of the program.

All access to a static is safe, but there are a number of restrictions on statics:

The type must have the Sync trait bound to allow thread-safe access. Statics allow using paths to statics in the constant expression used to initialize them, but statics may not refer to other statics by value, only through a reference. Constants cannot refer to statics.



我会像这样重写您的代码:
pub struct WebCam {
    id: u8,
}

impl WebCam {
    fn new() -> (Self, bool) {
        (WebCam { id: 1u8 }, false)
    }
}

pub fn main() {
    let (cam, is_running) = WebCam::new();
    println!("{} {}", cam.id, is_running);
}

这也适用:
pub struct WebCam {
    id: u8,
}

impl WebCam {
    fn new() -> (Self, bool) {
        (WebCam { id: 1u8 }, false)
    }
}
static mut IS_RUNNING: bool = false;
static mut WEB_CAM: WebCam = WebCam { id: 0u8 };

pub fn main() {
    let (cam, is_running) = WebCam::new();

    unsafe {
        IS_RUNNING = is_running;
        WEB_CAM.id = cam.id;
    }

    println!("{} {}", cam.id, is_running);
}

关于rust - 如何在Rust中为返回的元组设置静态生存期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60050584/

相关文章:

process - 如何在 Rust 中终止 Windows 上正在运行的子进程?

rust - 在单独的模块中使用时使用未声明的类型或模块 `std`

rust - 有没有办法强制从特定堆栈帧返回后不使用 Rust 原始指针?

C++ 标准 : end of lifetime

swift - 如何手动清零内存?

c++ - 使用智能指针作为 "non-owning references"有什么优缺点?

multithreading - 为什么我看不到 thread::spawn 内部打印的任何输出?

rust - 为什么生成在MPSC channel 上迭代的线程的程序永远不会退出? [复制]

rust - 实现一个 trait 方法,为拥有的类型返回一个有界的生命周期引用

rust - 阐明在函数签名中将两个对不同范围的引用对象的引用绑定(bind)到相同生命周期的含义