相关疑难解决方法(0)

这个错误是由于编译器对RefCell的特殊了解吗?

fn works<'a>(foo: &Option<&'a mut String>, s: &'a mut String) {}
fn error<'a>(foo: &RefCell<Option<&'a mut String>>, s: &'a mut String) {}

let mut s = "hi".to_string();

let foo = None;
works(&foo, &mut s);

// with this, it errors
// let bar = RefCell::new(None);
// error(&bar, &mut s);

s.len();
Run Code Online (Sandbox Code Playgroud)

如果我在注释中添加两行,则会发生以下错误:

error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable
  --> <anon>:16:5
   |
14 |     error(&bar, &mut s);
   |                      - mutable borrow occurs here
15 |     
16 |     s.len(); …
Run Code Online (Sandbox Code Playgroud)

rust borrow-checker

10
推荐指数
1
解决办法
140
查看次数

Rust编译器如何知道`Cell`有内部可变性?

请考虑以下代码(Playground版本):

use std::cell::Cell;

struct Foo(u32);

#[derive(Clone, Copy)]
struct FooRef<'a>(&'a Foo);

// the body of these functions don't matter
fn testa<'a>(x: &FooRef<'a>, y: &'a Foo) { x; }
fn testa_mut<'a>(x: &mut FooRef<'a>, y: &'a Foo) { *x = FooRef(y); }
fn testb<'a>(x: &Cell<FooRef<'a>>, y: &'a Foo) { x.set(FooRef(y)); }

fn main() {
    let u1 = Foo(3);
    let u2 = Foo(5);
    let mut a = FooRef(&u1);
    let b = Cell::new(FooRef(&u1));

    // try one of the following 3 statements
    testa(&a, &u2); …
Run Code Online (Sandbox Code Playgroud)

mutability rust

6
推荐指数
2
解决办法
257
查看次数

标签 统计

rust ×2

borrow-checker ×1

mutability ×1