Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a Vec into a function by reference

Tags:

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! } 
like image 453
Syntactic Fructose Avatar asked Jun 08 '14 03:06

Syntactic Fructose


People also ask

Can you pass a vector by reference?

In the case of passing a vector as a parameter in any function of C++, the things are not different. We can pass a vector either by value or by reference.

How to pass a vector to a function in C?

In c, you cannot pass a variable by reference. It's always by value. The problem is that arrays, are converted into pointers to their first element, so you can modify the original object through the pointer inside the function.


1 Answers

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); 
like image 167
Vladimir Matveev Avatar answered Oct 14 '22 13:10

Vladimir Matveev