0

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

6
  • You might be looking for interior mutability Commented Jul 9, 2020 at 21:39
  • It still possible to change inner value: fn f(x: &RefCell<Vec<u8>>) { *x.borrow_mut() = Vec::new(); } Commented Jul 9, 2020 at 21:41
  • 1
    This is not possible in Rust. Any method that borrows a value mutably can reassign it. Even Vec::push can copy the content of the Vec to a new location and replace the old Vec with the new one. This happens when there is not enough remaining capacity. Commented Jul 9, 2020 at 22:06
  • This sounds like a X/Y problem. Maybe we can help you better if you tell us what you're trying to achieve? Commented Jul 9, 2020 at 22:07
  • @aloso Im not trying to achieve anything just discussing language semantics. I'm just exploring language. Commented Jul 10, 2020 at 8:49

1 Answer 1

7

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.