我有以下代码:
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]
,所以该切片应该是可变的,但它却不是。我知道一定有一个简单的解决方法,但我已经尽力了,但无法使其工作。
thread_rng().shuffle
已经被弃用了。你知道我们现在应该如何打乱一个向量吗?(我想我们应该使用一个trait,但我在 Rust 中还没有足够的经验来知道如何做到这一点。) - J-LRng::shuffle
方法已被移除。现在需要使用SliceRandom::shuffle
方法。 - Brooke Jackson