1

I can use mutable reference for complicated types but not for simple data types. For example x (u32) in myfn:

fn main() {
    let mut x: u32 = 10;
    myfn(&mut x);
    println!("{}", x);
}

fn myfn(x: &mut u32) {
    x = 20;
  //^^ expected `&mut u32`, found integer
  // help: consider dereferencing here
  // to assign to the mutable borrowed piece of memory
  // *x = 20;
}

Is this happening because the simple type is always a copy? If so, why I can use the reference for immutable.

ICE
  • 1,667
  • 2
  • 21
  • 43

1 Answers1

3

Since x is a reference inside myfn, you need to dereference it before assignment. You're not assigning to x, you're assigning to the value that x refers to:

fn myfn(x: &mut u32) {
    *x = 20;
}

The compiler even shows this solution in its error message.

Explicit dereferencing is often unnecessary, for example in method calls, thanks to the Deref trait. But if you want to assign a new value, you need the explicit * there.

Thomas
  • 174,939
  • 50
  • 355
  • 478