I'm trying to convert a mutable vector to an immutable vector in Rust. I thought this would work but it doesn't:
let data = &mut vec![];
let x = data; // I thought x would now be an immutable reference
How can I turn a mutable reference into an immutable binding?
Back to Rust. A mutable reference is a borrow to any type mut T , allowing mutation of T through that reference. The below code illustrates the example of a mutable variable and then mutating its value through a mutable reference ref_i .
mut stands for mutable. You are telling the Rust compiler that you will be changing this variable. What's nice is that Rust holds you to this contract. If you declare a variable using mut and never change it you'll see this warning.
The fields of a struct share its mutability, so foo. bar = 2; would only be valid if foo was mutable. Adding pub to a field makes it visible to code in other modules, as well as allowing it to be directly accessed and modified. Tuple structs are similar to regular structs, but its fields have no names.
Cell<T> provides methods to retrieve and change the current interior value: For types that implement Copy , the get method retrieves the current interior value. For types that implement Default , the take method replaces the current interior value with Default::default() and returns the replaced value.
Dereference then re-reference the value:
fn main() {
let data = &mut vec![1, 2, 3];
let x = &*data;
}
For what your code was doing, you should probably read What's the difference in `mut` before a variable name and after the `:`?. Your variable data
is already immutable, but it contains a mutable reference. You cannot re-assign data
, but you can change the pointed-to value.
How can I turn a mutable reference into an immutable binding?
It already is an immutable binding, as you cannot change what data
is.
The other solution that works now is to specify the type of x:
fn main() {
let data = &mut vec![1, 2, 3];
let x: &_ = data;
println!("{x:?}");
// This will fail as x immutable
// *x = vec![]
}
When you don't specify the type, the compiler assumes you want the same type, which happens to be a &mut Vec<_>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With