snippetrustMajor
How to make a Rust mutable reference immutable?
Viewed 0 times
howmutableimmutablerustreferencemake
Problem
I'm trying to convert a mutable vector to an immutable vector in Rust. I thought this would work but it doesn't:
How can I turn a mutable reference into an immutable binding?
let data = &mut vec![];
let x = data; // I thought x would now be an immutable referenceHow can I turn a mutable reference into an immutable binding?
Solution
Dereference then re-reference the value:
For what your code was doing, you should probably read What's the difference in
How can I turn a mutable reference into an immutable binding?
It already is an immutable binding, as you cannot change what
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.Code Snippets
fn main() {
let data = &mut vec![1, 2, 3];
let x = &*data;
}Context
Stack Overflow Q#41366896, score: 87
Revisions (0)
No revisions yet.