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

Why can't the above be:

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

I don't need a mutable reference, just a mutable value.

I get a syntax error when I try this:

let sets = [
        mut HashSet::<char>::new(),
        mut HashSet::<char>::new(),
        mut HashSet::<char>::new(),
    ];
1
  • 5
    let mut sets: [HashSet<char>; 3] = Default::default(); is a shorter/less repetitive way to initialize that, by the way. Commented Dec 11, 2022 at 2:34

1 Answer 1

8

mut refers to if a variable is mutable, where as &mut refers to a mutable reference. So you can use mut variable_name or &mut Type, but not mut Type.

If you want the array to be mutable, you can specify it like this. This produces a mutable HashSet<char> array of length 3.

let mut sets = [
        HashSet::<char>::new(),
        HashSet::<char>::new(),
        HashSet::<char>::new(),
    ];
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly this. In the first example, you have an immutable array of type [&mut HashSet]. The elements of the array are "mutable references to HashSet". In the answer here, the elements of the array are of type HashSet, and the sets name is declared as mutable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.