Skip to content

Instantly share code, notes, and snippets.

@bugaevc bugaevc/
Last active May 1, 2016

What would you like to do?
// 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
// 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 {
// 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
// v is still completely ours
println!("(2) We still have v: {}, {}, ...", v[0], v[1]);
// exacly the same here
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
You can’t perform that action at this time.