1

This code works as expected in Rust 1.27.2:

struct X {
    a: String,
    b: String,
}

impl X {
    fn func(mut self: Self) -> String {
        let _a = self.a;
        self.a = "".to_string();
        self.b
    }
}

fn main() {
    let x = X {
        a: "".to_string(),
        b: "".to_string(),
    };
    x.func();
}

Using the same compiler version, the X instance is now boxed. Even without trying to mutate the partial object, the borrow checker stops reasoning behind the self:

struct X {
    a: String,
    b: String,
}

impl X {
    fn func(self: Box<Self>) -> String {
        let _a = self.a;
        self.b
    }
}

fn main() {
    let x = Box::new(X {
        a: "".to_string(),
        b: "".to_string(),
    });
    x.func();
}

Error message:

error[E0382]: use of moved value: `self`
 --> src/main.rs:9:9
  |
8 |         let _a = self.a;
  |             -- value moved here
9 |         self.b
  |         ^^^^^^ value used here after move
  |
  = note: move occurs because `self.a` has type `std::string::String`, which does not implement the `Copy` trait

Is it by design that the boxed objects cannot be partially borrowed or is it a regression in the ongoing refactoring of the borrow checker?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
wigy
  • 2,174
  • 19
  • 32
  • I believe your question is answered by the answers of [Dereferencing boxed struct and moving its field causes it to be moved](https://stackoverflow.com/q/40319313/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jul 31 '18 at 15:53
  • See also [Collaterally moved error when deconstructing a Box of pairs](https://stackoverflow.com/q/28466809/155423) – Shepmaster Jul 31 '18 at 15:57
  • Okay, these linked questions led me to a solution, but onyl indirectly. Should I answer myself, or will you compile an answer that `let x = *self; let _a = x.a; x.b` as a method body compiled properly? I was looking for interactions between partial moves and boxing in the language. – wigy Jul 31 '18 at 16:00
  • https://play.rust-lang.org/?gist=4ae457f5f2ca34b419578242799352dc&version=stable&mode=debug&edition=2015 – wigy Jul 31 '18 at 16:02
  • How do you mean "indirectly"? That's literally the implementation of `pub fn pop` in the first question. – Shepmaster Jul 31 '18 at 17:00
  • You are completely right, I was jumping to the error message in that post directly and read only the non-working implementation. End-of-day problems :wink: – wigy Aug 01 '18 at 07:24

0 Answers0