首页 文章

为什么`Cell特别适用于借阅检查器? [重复]

提问于
浏览
1

这个问题在这里已有答案:

我有 CellUnsafeCell / RefCell / ...)参考的生命周期问题 . 根据我的理解,这段代码应该编译:

fn test1<'a, 'b: 'a>(x: Cell<&'b u32>) {
    let x2: Cell<&'a u32> = x;
}

但它会产生错误:

error[E0308]: mismatched types
 --> src/main.rs:4:29
  |
4 |     let x2: Cell<&'a u32> = x;
  |                             ^ lifetime mismatch
  |
  = note: expected type `std::cell::Cell<&'a u32>`
             found type `std::cell::Cell<&'b u32>`
note: the lifetime 'a as defined on the function body at 3:1...
 --> src/main.rs:3:1
  |
3 | / fn test1<'a, 'b: 'a>(x: Cell<&'b u32>) {
4 | |     let x2: Cell<&'a u32> = x;
5 | | }
  | |_^
note: ...does not necessarily outlive the lifetime 'b as defined on the function body at 3:1
 --> src/main.rs:3:1
  |
3 | / fn test1<'a, 'b: 'a>(x: Cell<&'b u32>) {
4 | |     let x2: Cell<&'a u32> = x;
5 | | }
  | |_^

我认为在 <> 中的 : 并不是众所周知的运算符,但我在尝试解决问题时在某些RFC中找到了它 .

我应该可以制作一个寿命更短的 Cell 更长的一个 . 当我用一些虚拟包装替换 Cell 类型时,一切正常,所以从我的实验中看来 CellUnsafeCell 等)在处理参考生命周期时会被特别处理 .

这不是我原来的问题 . 我希望在多个结构之间有一些共享状态 - 一个带有 RefCell 的主结构和一个引用 RefCell 的子结构但是我不能在没有为整个对象的生命周期借用自己的情况下获得借用检查器 . 看到:

struct A<'a> {
    x: RefCell<&'a u32>,
}

impl<'a> A<'a> {
    fn new(x: &'a u32) -> A<'a> {
        A { x: RefCell::new(x) }
    }

    fn foo(&self) -> B<'a> {
        B { x: &self.x }
    }
}

struct B<'a> {
    x: &'a RefCell<&'a u32>,
}

如果我在 foo 中将生命 'a 添加到 self ,它会编译,但是对于此代码失败:

let fs = A::new(&x);
{
    fs.foo();
}
let fs2 = fs;

错误:错误[E0505]:无法移出 fs ,因为它是借来的

是否有其他方法来实现对象之间的共享状态?我正在使用单个线程,所以现在没有同步问题 .

1 回答

  • 3

    正如评论中所解释的那样,我的问题是由Cell type invariance引起的 . 我设法通过使用两个生命周期解决我原来的问题,而不是到处使用相同的生命周期 . 现在 &selffoo 借用的寿命比 'a 短:

    struct A<'a> {
        x: RefCell<&'a u32>,
    }
    
    impl <'a> A<'a> {
        fn new(x: &'a u32) -> A<'a> {
            A {
                x: RefCell::new(x),
            }
        }
    
        fn foo<'b>(&'b self) -> B<'b, 'a> {
            B {
                x: &self.x,
            }
        }
    }
    
    struct B<'b, 'a: 'b> {
        x: &'b RefCell<&'a u32>,
    }
    

相关问题