[英]How to make a Rust mutable reference immutable?
I'm trying to convert a mutable vector to an immutable vector in Rust.我正在尝试将可变向量转换为 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;
}
For what your code was doing, you should probably read What's the difference in `mut` before a variable name and after the `:`? 对于你的代码正在做什么,你应该阅读变量名之前和`:`之后的`mut`的区别是什么? .
。 Your variable
data
is already immutable, but it contains a mutable reference. 您的变量
data
已经是不可变的,但它包含一个可变引用。 You cannot re-assign data
, but you can change the pointed-to value. 您无法重新分配
data
,但可以更改指向的值。
How can I turn a mutable reference into an immutable binding?
如何将可变引用转换为不可变绑定?
It already is an immutable binding, as you cannot change what data
is. 它已经是一个不可变的绑定,因为你无法改变
data
。
The other solution that works now is to specify the type of x:现在可行的另一个解决方案是指定 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<_>
.当您不指定类型时,编译器会假定您想要相同的类型,这恰好是
&mut Vec<_>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.