0

I have a piece of code that looks like this:

struct Block {
    x: f32,
    y: f32,
    width: f32,
    height: f32,
    color: Color,
}

let mut blocks: Vec<Block> = Vec::new();

for block in blocks.iter() {
    block.x = 0.0 - block.width;
}

I am trying to change the x of all the blocks in the list but it gives an error:

error[E0594]: cannot assign to `block.x` which is behind a `&` reference
  --> src/main.rs:14:9
   |
13 |     for block in blocks.iter() {
   |                  ------------- this iterator yields `&` references
14 |         block.x = 0.0 - block.width;
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `block` is a `&` reference, so the data it refers to cannot be written

How do I fix this?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Rik Smits
  • 31
  • 7
  • 5
    iter_mut(). I advice you read the official book – Stargateur Apr 05 '21 at 12:49
  • It's hard to answer your question because it doesn't include a [MRE]. We can't tell what crates (and their versions), types, traits, fields, etc. are present in the code. It would make it easier for us to help you if you try to reproduce your error on the [Rust Playground](https://play.rust-lang.org) if possible, otherwise in a brand new Cargo project, then [edit] your question to include the additional info. There are [Rust-specific MRE tips](//stackoverflow.com/tags/rust/info) you can use to reduce your original code for posting here. Thanks! – Shepmaster Apr 05 '21 at 13:41

0 Answers0