[Rust] Reference Types in Rust
Learn how to create references in Rust using the borrow-operator &
and when they are useful.
For a more thorough explanation of references and their characteristics, check out this blog post: https://blog.thoughtram.io/references-in-rust/
let name: String = String::from("wzt");
let ref_name: &String = &name; // now refName points to string "wzt"
If we use String directly as a param of a function, we will have borrowing problem, for example:
fn main() {
let name = String::from("wzt");
let ref_name = &name;
say_hi(name);
println!("main {}", name) // Error: borrow of moved value: `name`, value borrowed here after move
}
fn say_hi(name: String) {
println!("Hello {}!", name)
}
This is because when we pass name
to say_hi
function, say_hi
function owns the name
, and when function ends, name
will be destoried. That's why you cannot print name
, after say_hi
function call.
In order to solve the problem, we can pass by reference:
fn main() {
let name = String::from("wzt");
let ref_name = &name;
say_hi(ref_name);
println!("main {}", ref_name) // OK
fn say_hi(name: &String) {
println!("Hello {}!", name)
}