1

How can I change the value of a field in an instance of a nested structure?

// Do Not Change - Start

struct Base {
    val: String,
}

struct Level1 {
    val: Base,
}

struct Level2 {
    val: Level1,
}

// Do Not Change - End

fn main() {
    let x = Level2 {
        val: Level1 {
            val: Base {
                val: "World".to_string(),
            },
        },
    };

    println!(" Hello {}", x.val.val.val);

    x.val.val.val = "Moon".to_string();

    println!(" Hello {}", x.val.val.val);
}

playground

error[E0594]: cannot assign to field `x.val.val.val` of immutable binding
  --> src/main.rs:28:5
   |
18 |     let x = Level2 {
   |         - help: make this binding mutable: `mut x`
...
28 |     x.val.val.val = "Moon".to_string();
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot mutably borrow field of immutable binding
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Peter Prographo
  • 1,141
  • 1
  • 10
  • 27

1 Answers1

3

I strongly recommend that you go back and re-read The Rust Programming Language, especially the chapter about variables and mutability.


Do as the compiler tells you:

 help: make this binding mutable: `mut x`
let mut x = Level2 {
    val: Level1 {
        val: Base {
            val: "World".to_string(),
        },
    },
};

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Yes obviously. But I already have the variable x, can't change it. Can I make a copy that is mutable? – Peter Prographo Oct 29 '18 at 17:35
  • @PeterPrographo *can't change it* — why can't you? It's clearly outside of the "Do Not Change" section in your code. – Shepmaster Oct 29 '18 at 17:37
  • Obviously this isn't the real code, it's a "verifiable, complete" version. The real code is 1000s of lines. – Peter Prographo Oct 29 '18 at 17:40
  • @PeterPrographo it's impossible for there to be a local variable which the compiler prohibits you from adding `mut` to it. – Shepmaster Oct 29 '18 at 17:48
  • 3
    @PeterPrographo if you have a 1000-line function (please don't) and want it to be immutable for part and mutable for the other, you can rebind it either way `let mut x = x` / `let x = x`, but this is reasonably uncommon. – Shepmaster Oct 29 '18 at 17:49
  • 3
    @PeterPrographo note that a [MCVE]'s definition of *complete* is "all information necessary to reproduce the problem is included". This answer addresses everything you've provided in the question. We simply don't have the ability to generate random permutations of code in the hopes that we stumble upon one that matches the code you actually have. Feel free to check out the [Rust-specific tips](//stackoverflow.com/tags/rust/info) for reducing a problem into a MCVE as well. – Shepmaster Oct 29 '18 at 17:54