Passing Rust Vecs to functions

In a C++ main() function one can define the C++ equivalent of Rust statement
let mut data = vec![f64::default(); size ];
..push() some initial values to data..
Then call function fn1(data)
.. data gets passed by reference, so any changes fn1() makes to data are visible to main() even though fn1() returns nothing

call function fn2(data) any changes fn2() makes to the modified data are also visible to main() even though fn2() returns nothing
.. at this point the initial data values were modified two times

? How does one achieve the same thing using Rust ??
calling function fn1(data) passes ownership of data to fn1
so one can not execute fn2(data) because the Rust main() no longer has access to data

? Do we get around this by defining
fn1(data) -> Vec {.. make changes data... return data; }
then write :
data2 : Vec = fn1 (data);
data3 : Vec = fn2 (data2);
.. again we must define fn2(data) -> Vec {.. make changes data... return data; }

OR ?

If you pass a mutable reference to a value, that reference can be used to mutate the original value.

fn do_stuff(v: &mut Vec<i32>) {
    v.push(100);
    for element in v {
        *element += 5;
    }
}

fn main() {
    let mut v = vec![1, 2, 3];
    do_stuff(&mut v);
    
    assert_eq!(v, [6, 7, 8, 105]);
}
1 Like

precisely what I need to duplicate C++ behavior

@AA_BB, you might want to take a look at this post

in particular, you can format code blocks

// like this one
fn foo() -> Bar { todo!() }

with three backticks

```
// like this one
fn foo() -> Bar { todo!() }
```

and inline code snippets, e.g. identifiers or small + expressions or Rust types like Vec<String> with single backticks

and inline code snippets, e.g. `identifiers` or `small + expressions`
or Rust types like `Vec<String>` with single backticks
1 Like

Thanks for the post..I wondered anout how to enter code in posts