Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Rust mutable reference immutable?

Tags:

rust

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?

like image 284
jbrown Avatar asked Dec 28 '16 17:12

jbrown


People also ask

What is a mutable reference in Rust?

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 .

What does mut do in Rust?

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.

Are struct fields mutable Rust?

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.

What is cell in Rust?

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.


2 Answers

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.

like image 124
Shepmaster Avatar answered Oct 18 '22 19:10

Shepmaster


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<_>.

like image 3
Penguin Brian Avatar answered Oct 18 '22 20:10

Penguin Brian