Skip to content

Instantly share code, notes, and snippets.

@proudlygeek
Last active July 18, 2016 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save proudlygeek/3bad6e37aaca9258ef079ac5bf50a934 to your computer and use it in GitHub Desktop.
Save proudlygeek/3bad6e37aaca9258ef079ac5bf50a934 to your computer and use it in GitHub Desktop.
Rust Ownership / Borrow
fn sum_vectors(a: Vec<i32>, b: Vec<i32>) -> (Vec<i32>, Vec<i32>, Vec<i32>) {
let mut result: Vec<i32> = vec![0; 3];
for (i, _item) in a.iter().enumerate() {
result[i] = a[i] + b[i];
}
(a, b, result)
}
fn sum_vectors_borrow(a: &Vec<i32>, b: &Vec<i32>) -> Vec<i32> {
let mut result: Vec<i32> = vec![0; 3];
for (i, _item) in a.iter().enumerate() {
result[i] = a[i] + b[i];
}
result
}
fn add_element(a: &mut Vec<i32>, el: i32) {
a.push(el);
}
fn print_vector(a: &Vec<i32>) {
for item in a {
println!("{}", item);
}
}
fn main() {
println!("Owned:");
let (a, b): (Vec<i32>, Vec<i32>) = (vec![1, 2, 3], vec![4, 5, 6]);
let (a, b, c) = sum_vectors(a, b);
print_vector(&a);
print_vector(&b);
print_vector(&c);
println!("Borrow:");
let c = sum_vectors_borrow(&a, &b);
print_vector(&a);
print_vector(&b);
print_vector(&c);
println!("Mutable ref");
let mut d = vec![1, 2];
add_element(&mut d, 3);
print_vector(&d);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment