为什么 Rust 中的数组元素不能有可变值?

use*_*630 3 rust

let sets = [
        &mut HashSet::<char>::new(),
        &mut HashSet::<char>::new(),
        &mut HashSet::<char>::new(),
    ];
Run Code Online (Sandbox Code Playgroud)

为什么上面不能是:

let sets = [
        mut HashSet::<char>::new(),
        mut HashSet::<char>::new(),
        mut HashSet::<char>::new(),
    ];
Run Code Online (Sandbox Code Playgroud)

我不需要可变引用,只需要可变值。

当我尝试这样做时,出现语法错误:

let sets = [
        mut HashSet::<char>::new(),
        mut HashSet::<char>::new(),
        mut HashSet::<char>::new(),
    ];
Run Code Online (Sandbox Code Playgroud)

Loc*_*cke 8

mut指变量是否可变,其中 as&mut指可变引用。所以你可以使用mut variable_nameor &mut Type,但不能使用mut Type。

如果你希望数组是可变的,你可以这样指定。这会生成一个HashSet<char>长度为 3 的可变数组。

let mut sets = [
        HashSet::<char>::new(),
        HashSet::<char>::new(),
        HashSet::<char>::new(),
    ];
Run Code Online (Sandbox Code Playgroud)