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

3
let sets = [
        &mut HashSet::<char>::new(),
        &mut HashSet::<char>::new(),
        &mut HashSet::<char>::new(),
    ];

为什么上面的内容不能是这样的:
let sets = [
        mut HashSet::<char>::new(),
        mut HashSet::<char>::new(),
        mut HashSet::<char>::new(),
    ];

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

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

let sets = [
        mut HashSet::<char>::new(),
        mut HashSet::<char>::new(),
        mut HashSet::<char>::new(),
    ];

5
顺便说一下,let mut sets: [HashSet<char>; 3] = Default::default(); 是初始化的一种更短、更少重复的方式。 - Ry-
1个回答

8

mut 指的是变量是否可变,而 &mut 指的是可变引用。因此你可以使用 mut variable_name 或者 &mut Type,但不能使用 mut Type

如果想要数组是可变的,可以像这样指定。这将生成一个长度为 3 的可变 HashSet<char> 数组。

let mut sets = [
        HashSet::<char>::new(),
        HashSet::<char>::new(),
        HashSet::<char>::new(),
    ];

就是这样。在第一个示例中,您有一个类型为[&mut HashSet]的不可变数组。数组的元素是“对HashSet的可变引用”。在这里的答案中,数组的元素是HashSet类型,并且sets名称被声明为可变。 - cadolphs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接