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 doesn't Rust demand dereferencing on using not mut reference passed into function?

When I see this code everything is clear. We have a reference that we should dereference to manipulate data inside of it.

fn twice(x: &mut u8) {   
    *x = *x * 2;
}

But why does the following code compile?

fn twice(x: &u8) -> u8 {
    x * 2
}

Why doesn’t Rust demands from me to dereference x here and requires it in the first example?

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 :

Rust has a Mul<u8> implementation for &u8. This means that you can multiply an &u8 and u8 to get a u8, with no dereferencing needed. However, for whatever reason, there’s no instance for &mut u8, so the following will fail:

fn twice(x: &mut u8) -> u8 {
    x * 2
}
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