Skip to content

Instantly share code, notes, and snippets.

@stevej
Created January 8, 2017 22:50
Show Gist options
  • Save stevej/100479ca8dea0495070a2f754537ad02 to your computer and use it in GitHub Desktop.
Save stevej/100479ca8dea0495070a2f754537ad02 to your computer and use it in GitHub Desktop.
Rust for the Experienced Programmer. Lesson 2: references vs values
#[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);
}
@stevej
Copy link
Author

stevej commented Jan 9, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment