Created
January 8, 2017 22:50
-
-
Save stevej/100479ca8dea0495070a2f754537ad02 to your computer and use it in GitHub Desktop.
Rust for the Experienced Programmer. Lesson 2: references vs values
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
#[derive(Debug)] | |
struct Person { | |
id: u64, | |
name: String, | |
} | |
impl Person { | |
// Because we're passing a value, we take ownership of it. If we want to give | |
// ownership back, we have to return it. | |
fn set_name(mut self, new_name: String) -> Person { | |
self.name = new_name; | |
return self; | |
} | |
// Since we're borrowing a reference, we don't take ownership. | |
fn name_with_greeting(&self) -> String { | |
return "Greetings, ".to_string() + self.name.as_str(); | |
} | |
// By taking a mutable reference, we can change it and not have to return | |
// it. The rule: the compiler will only hand out a single mutable reference | |
// at once. | |
fn set_name2(&mut self, new_name: String) { | |
// This is automatically deferenced by Rust. | |
self.name = new_name; | |
} | |
} | |
fn main() { | |
// Since we're planning to change a field, we have to mark this as mutable | |
let mut stevej = Person { | |
id: 1, | |
name: "Steve Jenson".to_string(), | |
}; | |
stevej.name = "Stan Jergsen".to_string(); | |
println!("{:?}", stevej); | |
// This is a common Rust idiom where ownership changes are handled by | |
// using assignment. Let's walk through why. | |
let mut stevej = stevej.set_name("Frob Johnson".to_string()); | |
println!("{:?}", stevej); | |
println!("{:?}", stevej.name_with_greeting()); | |
stevej.set_name2("Ferg Johannsen".to_string()); | |
// Because set_name2 takes a reference, a borrow happened instead of | |
// an ownership change. | |
println!("{:?}", stevej); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://play.rust-lang.org/?gist=100479ca8dea0495070a2f754537ad02