[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 nameto say_hifunction, say_hifunction owns the name, and when function ends, namewill be destoried. That's why you cannot print name, after say_hifunction 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)
}

 

posted @ 2024-02-20 22:29  Zhentiw  阅读(3)  评论(0编辑  收藏  举报