How to make a Rust mutable reference immutable?

后端 未结 1 631
一个人的身影
一个人的身影 2021-02-05 04:02

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;              


        
相关标签:
1条回答
  • 2021-02-05 04:44

    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.

    0 讨论(0)
提交回复
热议问题