-4

I found this answer to a related question, but it does not help me. According to my understanding the following code should work: container_options is not just a mutable reference, it is owned. I should be able to extract a mutable reference to it or even just edit it directly, but the compiler refuses to accept anything I tried. I have no idea where the problem is and hope that someone else does.

Edit: I kinda found a workaround, so this is solved.

fn update_container_options_with_paths(
    container_options: Vec<ContainerOption>,
    path_options: &Vec<Rc<PathOption>>,
) {
    for container_index in 0..container_options.len() {
        let container_option = &mut container_options[container_index];
        container_option.compatible_path_options = 0;
        for (path_index, path_option) in path_options.iter().enumerate() {
            if PathOption::decode_loading_mask(
                path_option.summary.compatible_container_options,
                container_index,
            ) {
                container_option.set_compatible(path_index);
            }
        }
    }
}
  • 2
    Please provide a MCE and the full error message. – Chayim Friedman May 26 '22 at 09:49
  • 1
    "*Edit: I kinda found a workaround, so this is solved*"—then please post as an answer to your own question, as it could help others with similar problems in the future. – eggyal May 26 '22 at 14:28

1 Answers1

2

I should be able to extract a mutable reference to it or even just edit it directly, but the compiler refuses to accept anything I tried. I have no idea where the problem is and hope that someone else does.

The compiler tells you exactly what the issue is and how to fix it:

error[E0596]: cannot borrow `container_options` as mutable, as it is not declared as mutable
 --> src/lib.rs:5:37
  |
3 | fn update_container_options_with_paths(container_options: Vec<()>, path_options: &Vec<Rc<()>>) {
  |                                        ----------------- help: consider changing this to be mutable: `mut container_options`
4 |     for container_index in 0..container_options.len() {
5 |         let container_option = &mut container_options[container_index];
  |                                     ^^^^^^^^^^^^^^^^^ cannot borrow as mutable

For more information about this error, try `rustc --explain E0596`.

Even when something is owned, Rust still has a concept of mutable v non-mutable bindings, and you can only get a mutable reference from a mutable binding.

This is mostly indicative as you can trivially change it e.g.

let mut a = a;

but it's still non optional.

And I don't understand the purpose of indexing into container_options, why not just container_options.iter_mut() or (iterating on) &mut container_options? It's not like it works any less than index_mut.

Masklinn
  • 34,759
  • 3
  • 38
  • 57