【发布时间】:2025-12-30 18:05:06
【问题描述】:
我有以下代码:
extern crate rand;
use rand::{thread_rng, Rng};
fn main() {
let mut vec: Vec<u32> = (0..10).collect();
let mut slice: &[u32] = vec.as_mut_slice();
thread_rng().shuffle(slice);
}
并得到以下错误:
error[E0308]: mismatched types
--> src/main.rs:9:26
|
9 | thread_rng().shuffle(slice);
| ^^^^^ types differ in mutability
|
= note: expected type `&mut [_]`
found type `&[u32]`
我想我明白向量和切片的内容是不可变的,这会导致这里出现错误,但我不确定。
as_mut_slice 的签名是pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T],所以切片应该是可变的,但不知何故它不是。
我知道必须有一个简单的解决方法,但我尽了最大努力却无法让它发挥作用。
【问题讨论】:
标签: iterator immutability rust mutability