如何使 Rust 可变引用不可变? [英] How to make a Rust mutable reference immutable?

查看:69
本文介绍了如何使 Rust 可变引用不可变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 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?

推荐答案

取消引用然后重新引用值:

Dereference then re-reference the value:

fn main() {
    let data = &mut vec![1, 2, 3];
    let x = &*data;
}

对于您的代码在做什么,您可能应该阅读变量名称之前和之后的 `mut` 有什么区别:`?.您的变量 data 已经是不可变的,但它包含一个可变引用.您不能重新分配 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?

它已经一个不可变的绑定,因为你不能改变data是什么.

It already is an immutable binding, as you cannot change what data is.

这篇关于如何使 Rust 可变引用不可变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆