softshipper
softshipper

Reputation: 34071

You can’t borrow a mutable reference to a read-only value

I bought the book Programming Rust: Fast, Safe Systems Development 2nd Edition a couple weeks ago to learn Rust. At the moment, I am struggling with the topic &T and mut &T.

In the book, the author has mentioned the following regarding to references:

You can’t borrow a mutable reference to a read-only value.

What does it mean? An example would be nice.

Upvotes: 2

Views: 409

Answers (2)

at54321
at54321

Reputation: 11708

In Rust, variables are immutable by default. You can only borrow variables as mutable if those variables themselves are declared as mutable.

Consider this example:

let x = 42;
let mut y = 42;
let _a = &x;  // This is fine
let _b = &mut x; // This is NOT 
let _c = &y;  // This is fine (even though y is mut)
let _d = &mut y;  // This is fine

Also note that it is not possible to have a mutable reference to a standard (immutable) reference to a mutable variable. Example:

let mut y = 42;
let r = &y;  // This is fine
let m = &mut r;  // This is NOT (cannot borrow `r` as mutable, as it is not declared as mutable)

Upvotes: 0

cafce25
cafce25

Reputation: 27236

You can't do the following:

let a = 99;
let b = &mut a;

Upvotes: 4

Related Questions