小编Jam*_*ell的帖子

unsafe 的这种使用是非常安全的吗?

我遇到了 Rust 借用检查器错误,我认为这是当前非词法生命周期实现的限制。我想写的代码看起来像这样:

struct Thing {
    value: i32
}

impl Thing {
    fn value(&self) -> &i32 {
        &self.value
    }
    fn increment(&mut self) {
        self.value += 1;
    }
}

/// Increments the value of `thing` if it is odd, and returns a reference to the value.
fn increment_if_odd(thing: &mut Thing) -> &i32 {
    let ref_to_value = thing.value();
    if (*ref_to_value % 2) == 0 {
        return ref_to_value;
    }
    thing.increment();  // fails to compile because the immutable borrow `ref_to_value` is still alive …
Run Code Online (Sandbox Code Playgroud)

unsafe rust borrow-checker

15
推荐指数
1
解决办法
617
查看次数

标签 统计

borrow-checker ×1

rust ×1

unsafe ×1