Last active
March 5, 2016 03:56
-
-
Save mdaisuke/16038b3238d64dbc53fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn take_ownership(v: Vec<i32>) { | |
} | |
fn borrow_ref(v: &Vec<i32>) { | |
} | |
fn main() { | |
// | |
// Ownership | |
// https://doc.rust-lang.org/stable/book/ownership.html | |
// | |
let v = vec![1, 2, 3]; | |
let v2 = v; | |
// use of moved value: `v` | |
//println!("v[0] is: {}", v[0]); | |
take_ownership(v2); | |
// use of moved value: `v2` | |
//println!("v2[0] is: {}", v2[0]); | |
// | |
// this is the `move` | |
// | |
// | |
// Copy trait | |
// | |
// copying is a full copy. | |
// all primitive types implement the Copy trait, | |
// that's why ownership is not moved. | |
let v = 1; | |
let v2 = v; | |
println!("v is: {}", v); | |
// | |
// References and Borrowing | |
// https://doc.rust-lang.org/stable/book/references-and-borrowing.html | |
// | |
let v1 = vec![1, 2, 3]; | |
// `&` is reference pointer to the value on the heap | |
borrow_ref(&v1); | |
println!("v1[0] = {}", v1[0]); | |
// if you need mutable reference, use `&mut` | |
let mut x = 5; | |
{ | |
//error: cannot assign to immutable borrowed content `*y` | |
//let y = &x; | |
let y = &mut x; | |
*y += 1; | |
} | |
println!("{}", x); | |
// | |
// borrowin rules | |
// - any borrow must last for a scope no greater than that of the owner | |
// - you may have one or the other of these two kinds of borrows, but not both at the same time | |
// - one or more references(&T) to a resource | |
// - exactly one mutable reference(&mut T) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment