How to pass a mutable vector as a function parameter in Rust?

I am implementing a small program that evaluates the Collatz hypothesis. As part of this, I have a function that I call recursively, I want to save the current evaluated number, determine whether it is odd or even (or complete, if it's just 1), execute this branch of the hypothesis, and then call yourself with a new number .

To do this, I wanted to pass a vector into this function and insert the current number into this vector, but it's hard for me to figure out how to pass a mutable link to the vector.

Here is the code I have:

fn evaluate_conjecture(number_to_be_evaluated: u64, mut intermediate_results: &Vec<u64>) -> u64 {
    intermediate_results.push(number_to_be_evaluated);

    if number_to_be_evaluated == 1 {
        0
    } else if number_to_be_evaluated % 2 == 1 {
        let odd_step_result = perform_odd_conjecture_step(number_to_be_evaluated);
        evaluate_conjecture(odd_step_result, intermediate_results) + 1
    } else {
        let even_step_result = perform_even_conjecture_step(number_to_be_evaluated);
        evaluate_conjecture(even_step_result, intermediate_results) + 1
    }
}

fn perform_odd_conjecture_step(_: u64) -> u64 {
    unimplemented!()
}

fn perform_even_conjecture_step(_: u64) -> u64 {
    unimplemented!()
}

but the actual part of my main

fn main() {
    let input_number = 42;
    let mut _intermediate_results: Vec<u64>;
    let number_of_steps = evaluate_conjecture(input_number, &_intermediate_results);
}

Here is the error I get

error[E0596]: cannot borrow '*intermediate_results' as mutable, as it is behind a '&' reference
 --> src/main.rs:2:5
  |
1 | fn evaluate_conjecture(number_to_be_evaluated: u64, mut intermediate_results: &Vec<u64>) -> u64 {
  |                                                                               --------- help: consider changing this to be a mutable reference: '&mut std::vec::Vec<u64>'
2 |     intermediate_results.push(number_to_be_evaluated);
  |     ^^^^^^^^^^^^^^^^^^^^ 'intermediate_results' is a '&' reference, so the data it refers to cannot be borrowed as mutable

How to pass this vector to a function so that I can change it with every function call?

+8
1

&T .

&mut T .

&Vec<u64> &mut Vec<u64> &_intermediate_results &mut _intermediate_results.

, ; , - . , .

+11

All Articles