我有以下代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
并得到以下错误:
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]`
Run Code Online (Sandbox Code Playgroud)
我想我明白向量和切片的内容是不可变的,这会导致错误,但我不确定.
签名as_mut_slice
是pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T]
,所以切片应该是可变的,但它不知何故.
我知道必须有一个简单的解决办法,但我尽我所能,无法让它发挥作用.