相关疑难解决方法(0)

不能将`self.x`借用为不可变因为`*self`也被借用为可变的

首先,让代码说:

#[derive(Debug)]
struct Bar;

#[derive(Debug)]
struct Qux {
    baz: bool
}

#[derive(Debug)]
struct Foo {
    bars: Vec<Bar>,
    qux: Qux,
}

impl Foo {
    fn get_qux(&mut self) -> &mut Qux {
        &mut self.qux
    }

    fn run(&mut self) {
        // 1. Fails:
        let mut qux = self.get_qux();

        // 2. Works:
        // let mut qux = &mut Qux { baz: false };

        // 3. Works:
        // let mut qux = &mut self.qux;

        let qux_mut = &mut qux;
        qux_mut.baz = true;

        for bar in …
Run Code Online (Sandbox Code Playgroud)

immutability mutability rust

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

为什么在&mut self中允许借用struct成员,而不是self到不可变方法?

如果我有一个封装两个成员的结构,并根据另一个更新一个,只要我这样做就可以了:

struct A {
    value: i64
}

impl A {
    pub fn new() -> Self {
        A { value: 0 }
    }
    pub fn do_something(&mut self, other: &B) {
        self.value += other.value;
    }
    pub fn value(&self) -> i64 {
        self.value
    }
}

struct B {
    pub value: i64
}

struct State {
    a: A,
    b: B
}

impl State {
    pub fn new() -> Self {
        State {
            a: A::new(),
            b: B { value: 1 }
        }
    }
    pub fn …
Run Code Online (Sandbox Code Playgroud)

rust memory-safety borrow-checker

7
推荐指数
1
解决办法
427
查看次数

为什么通过提取方法进行重构会触发借用检查器错误?

我的网络应用程序的体系结构可以简化为以下内容:

use std::collections::HashMap;

/// Represents remote user. Usually has fields,
/// but we omit them for the sake of example.
struct User;

impl User {
    /// Send data to remote user.
    fn send(&mut self, data: &str) {
        println!("Sending data to user: \"{}\"", data);
    }
}

/// A service that handles user data.
/// Usually has non-trivial internal state, but we omit it here.
struct UserHandler {
    users: HashMap<i32, User>,  // Maps user id to User objects.
    counter: i32  // Represents …
Run Code Online (Sandbox Code Playgroud)

rust borrow-checker

4
推荐指数
1
解决办法
122
查看次数