HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMajor

How to make a Rust mutable reference immutable?

Submitted by: @import:stackoverflow-api··
0
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:

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?

Solution

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.

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.