Skip to content

Instantly share code, notes, and snippets.

@bugaevc
Last active May 1, 2016 17:22
Show Gist options
  • Save bugaevc/a0e980c640dc428de686bc1426162380 to your computer and use it in GitHub Desktop.
Save bugaevc/a0e980c640dc428de686bc1426162380 to your computer and use it in GitHub Desktop.
// without borrowing
fn print_sum1(v: Vec<i32>) -> Vec<i32> {
println!("{}", v[0] + v[1]);
// returning v as a means of transferring ownership back
// by the way, there's no need to use "return" if it's the last line
// because Rust is expression-based
v
}
// with borrowing, explicit references
fn print_sum2(vr: &Vec<i32>) {
println!("{}", (*vr)[0] + (*vr)[1]);
// vr, the reference, is dropped here
// thus the borrow ends
}
// this is how you should actually do it
fn print_sum3(v: &Vec<i32>) {
println!("{}", v[0] + v[1]);
// same as in print_sum2
}
fn main() {
let mut v = Vec::new(); // creating the resource
for i in 1..1000 {
v.push(i);
}
// at this point, v is using
// no less than 4000 bytes of memory
// transfer ownership to print_sum and get it back after they're done
v = print_sum1(v);
// now we again own and control v
println!("(1) We still have v: {}, {}, ...", v[0], v[1]);
// take a reference to v (borrow it) and pass this reference to print_sum2
print_sum2(&v);
// v is still completely ours
println!("(2) We still have v: {}, {}, ...", v[0], v[1]);
// exacly the same here
print_sum3(&v);
println!("(3) We still have v: {}, {}, ...", v[0], v[1]);
// v is dropped and deallocated here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment