Skip to content

Instantly share code, notes, and snippets.

@piaoger
Last active October 17, 2016 09:53
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 piaoger/6108d7e52a715968beec6e8702d0ea4c to your computer and use it in GitHub Desktop.
Save piaoger/6108d7e52a715968beec6e8702d0ea4c to your computer and use it in GitHub Desktop.
rust-intro: borrow
// http://rustbyexample.com/scope/borrow.html
// https://is.gd/E0jeLL
fn simple_borrow() {
let mut v = vec!["A"];
{
// immutable borrow
let borrow = &v;
// borrow.push("B");
}
{
// mutable borrow
let mut borrow = &mut v;
borrow.push("C");
}
v.push("D");
println!("{:?}", v);
}
fn take_and_print(vec: Vec<i32>) {
for elem in vec.iter() {
println!("{}", elem)
}
// vec goes out of scope and it is taken
}
fn borrow_and_print(vec: &Vec<i32>) {
for elem in vec.iter() {
println!("{}", elem)
}
// vec borrow goes out of scope and ownership is returned
}
fn try_brrow_and_destory() {
let mut v = vec![1, 2, 3];
borrow_and_print(&v);
v.push(4);
take_and_print(v);
v.push(5);
}
// This function takes ownership of a box and destroys it
fn eat_box_i32(boxed_i32: Box<i32>) {
println!("Destroying box that contains {}", boxed_i32);
}
// This function borrows an i32
fn borrow_i32(borrowed_i32: &i32) {
println!("This int is: {}", borrowed_i32);
}
fn advanced_borrow() {
// Create a boxed i32, and a stacked i32
let boxed_i32 = Box::new(5_i32);
let stacked_i32 = 6_i32;
// Borrow the contents of the box. Ownership is not taken,
// so the contents can be borrowed again.
borrow_i32(&boxed_i32);
borrow_i32(&stacked_i32);
{
// Take a reference to the data contained inside the box
let _ref_to_i32: &i32 = &boxed_i32;
// Error!
// Can't destroy `boxed_i32` while the inner value is borrowed.
// eat_box_i32(boxed_i32);
// FIXME ^ Comment out this line
// `_ref_to_i32` goes out of scope and is no longer borrowed.
}
// `boxed_i32` can now give up ownership to `eat_box` and be destroyed
eat_box_i32(boxed_i32);
}
fn main() {
simple_borrow();
try_brrow_and_destory();
advanced_borrow();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment