Rust的所有权、借用、可变引用 -- 学习随笔

Rust所有权规则:

1. Rust中每一个变量都是自己值的所有者;

2. 每一个值在任一时刻只有一个所有者;

3. 所有者(变量)离开所属作用域后,这个值被丢弃;

fn main() {
    let s1 = String::from("Hello!");
    let s2 = s1;
    println!("s2 passed: {}", s2);
    println!("s1 failed: {}", s1); // value borrowed here after move
}

 

Rust中的借用(不让所有权发生转移 "&")

fn echo(s: &String) {
    println!("echo: {}", s);
}

fn main() {
    let s = String::from("A");
    echo(&s);
    // 可以正常输出
    println!("main output: {}", s);
}

 

Rust中的可变引用

fn change(s: &mut String) {
  s.push_str(" changed!");
}

fn main() {
  let mut s = String::from("variable-s");
  change(&mut s);
  println!("after change: {}", s);
}

同一时刻至多只能有一个可变引用

fn main() {
  let mut s = String::from("var s");
  let s_ref1 = &mut s;
  let s_ref2 = &mut s;
  println!("{}", s_ref1);
  println!("{}", s_ref2); // error: second mutable borrow occurs here
}

 

posted @ 2022-12-28 22:48  樊顺  阅读(53)  评论(0编辑  收藏  举报