Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I cannot use simple types as mutable reference

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading