user3205630
user3205630

Reputation: 67

Why can't I have mutable values in Rust in array elements?

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(),
    ];

Upvotes: 3

Views: 194

Answers (1)

Locke
Locke

Reputation: 8980

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(),
    ];

Upvotes: 8

Related Questions