Search code examples
rust

Passing a Vec into a function by reference


I'm having some trouble passing a Vec<u64> into a function without moving it. I have a function find_factors(mut n: u64, mut fctrs: Vec<u64>) and I am currently calling from main like so:

fn main() {
    let mut primeFactors: Vec<u64> = Vec::new();
    find_factors(1134 as u64, primeFactors);
}

I'm forced right now to loop through and print out my vector in the find_factors function because I'm not sure how to pass the Vec<u64> by reference instead of moving it. How could I accomplish this? Example of what I want to do:

fn main() {
    let mut primeFactors: Vec<u64> = Vec::new();
    find_factors(1134 as u64, primeFactors);

    //for ....
        //print vector in main!
}

Solution

  • If you don't need to add or remove elements from the vector, use slice (&[T]) or mutable slice (&mut [T]):

    fn find_factors(n: u64, prime_factors: &mut [u64]) { ... }
    
    let mut prime_factors: Vec<u64> = Vec::new();
    find_factors(1134 as u64, prime_factors.as_mut_slice());
    

    Immutable slices allow you to read elements or create subslices; mutable slices additionally allow to modify elements. But slices cannot grow - they are just a view into some vector.

    It looks like you need to append new elements to the vector. You won't be able to do it using slice, as I said; you need to pass the vector itself using mutable reference:

    fn find_factors(n: u64, prime_factors: &mut Vec<u64>) {
        // here you can call e.g. prime_factors.push(...)
    }
    
    let mut prime_factors: Vec<u64> = Vec::new();
    find_factors(1134 as u64, &mut prime_factors);