Skip to content

Instantly share code, notes, and snippets.

@horiajurcut
Created May 6, 2018 19:44
Show Gist options
  • Save horiajurcut/d5f67cbd41f7501e133b31fde0e3d719 to your computer and use it in GitHub Desktop.
Save horiajurcut/d5f67cbd41f7501e133b31fde0e3d719 to your computer and use it in GitHub Desktop.
Rust References
fn main() {
println!("References");
let mut alpha = String::from("hello");
let len = calculate_length(&alpha);
println!("The length of '{}' is {}.", alpha, len);
change(&mut alpha);
println!("alpha is now '{}' after borrowing", alpha);
// References allow you to refer to some value without taking ownership
// s is a pointer to alpha
// & = referencing, * = dereferencing
// Having references as function parameters -> borrowing
// References are immutable by default
// You can only have one mutable reference to a particular piece of data in a particular scope
// Dangling references
// Dangling pointer -> pointer that references a location in memory that may have been given
// to someone else
let ref_to_nothing = dangle();
println!("Ref to something = {}", ref_to_nothing);
// Rules of References
//
// 1. At any given time you can have either but not both of:
// a. one mutable reference
// b. any number of immutable references
// 2. References must always be valid
}
fn calculate_length(s: &String) -> usize {
s.len() // value is not dropped when reference goes out of scope -> not an owner
}
fn change(some_string: &mut String) {
some_string.push_str(", surprise");
}
// fn dangle() -> &String {
// let s = String::from("dangling");
// &s
// }
// s goes out of scope -> a reference to something that is dropped is a dangling reference
fn dangle() -> String {
let s = String::from("word");
s
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment