madabrowski
madabrowski

Reputation: 1561

How to make immutable variable pointing mutable data in Rust

I'm having trouble understand how to achieve following: I would like a reference to vector that i cannot change, containing data that i can change(c++ T* const equivalent) Is that achievable in rust syntax?

let mut a = Vec::new()
a.push(1) // should be allowed
a = Vec::new() // should be disallowed.

mut seems to be allowing mutability on both levels

Upvotes: 0

Views: 240

Answers (1)

harmic
harmic

Reputation: 30597

This:

let mut a = Vec::new()

does not create a reference to a vector; rather it creates a variable bound to the vector itself. It is the equivalent to this in C++:

std::vector<int> a;

If you want an immutable reference to a mutable vector, you would have something like this:

let mut a = vec![1,2,3];

let r = &mut a;
r.push(4);

In the above snippet, r is an immutable variable bound to a reference to the mutable vector a. If you try to re-assign r to be a reference to another vector:

let mut b = vec![4,5,6];

r=&mut b;
r.push(7);

you will get this error:

9 |     r=&mut b;
  |     ^^^^^^^^ cannot assign twice to immutable variable

Playground

Note however that due to the fact that Rust allows shadowing, you can use 'let' to create a new binding that shadows the old one in the same scope, so you could do this:

let mut a = vec![1, 2, 3];

let r = &mut a;
r.push(4);

let mut b = vec![4, 5, 6];
let r = &mut b;
r.push(7);

Upvotes: 7

Related Questions