Skip to content

Instantly share code, notes, and snippets.

@Clivern
Created August 15, 2021 17:45
Show Gist options
  • Save Clivern/c1128a78e66d9a9ceec0c9a3e3d5b054 to your computer and use it in GitHub Desktop.
Save Clivern/c1128a78e66d9a9ceec0c9a3e3d5b054 to your computer and use it in GitHub Desktop.
Rust Pass by Value and Reference
// Pass by refernce
fn double1(x: &mut [i32; 10]) {
for i in 0..10 {
x[i] += 2;
}
}
// Pass by value
fn double2(x: [i32; 10]) -> [i32; 10] {
let mut y: [i32; 10] = x;
for i in 0..10 {
y[i] += 2;
}
y
}
// Pass by value
fn double3(mut x: [i32; 10]) -> [i32; 10] {
for i in 0..10 {
x[i] += 2;
}
x
}
fn main() {
let mut ar: [i32; 10] = [3;10];
double1(&mut ar);
println!("{:?}", ar);
println!("{:?}", double2(ar));
println!("{:?}", double3(ar));
}
@Clivern
Copy link
Author

Clivern commented Aug 15, 2021

Standard Error
   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 1.57s
     Running `target/debug/playground`

Standard Output
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
[7, 7, 7, 7, 7, 7, 7, 7, 7, 7]
[7, 7, 7, 7, 7, 7, 7, 7, 7, 7]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment