借用值

As we saw before, instead of transferring ownership when calling a function, you can let a function borrow the value:

  1. #[derive(Debug)]
  2. struct Point(i32, i32);
  3. fn add(p1: &Point, p2: &Point) -> Point {
  4. Point(p1.0 + p2.0, p1.1 + p2.1)
  5. }
  6. fn main() {
  7. let p1 = Point(3, 4);
  8. let p2 = Point(10, 20);
  9. let p3 = add(&p1, &p2);
  10. println!("{p1:?} + {p2:?} = {p3:?}");
  11. }
  • add 函数“借用”两个点并返回一个新点。
  • 调用方会保留输入的所有权。

This slide should take about 10 minutes.

此幻灯片是对第 1 天引用材料的回顾,并稍作了扩展,添加了函数参数和返回值。

探索更多

关于栈返回的说明:

  • Demonstrate that the return from add is cheap because the compiler can eliminate the copy operation. Change the above code to print stack addresses and run it on the Playground or look at the assembly in Godbolt. In the “DEBUG” optimization level, the addresses should change, while they stay the same when changing to the “RELEASE” setting:

    1. #[derive(Debug)]
    2. struct Point(i32, i32);
    3. fn add(p1: &Point, p2: &Point) -> Point {
    4. let p = Point(p1.0 + p2.0, p1.1 + p2.1);
    5. println!("&p.0: {:p}", &p.0);
    6. p
    7. }
    8. pub fn main() {
    9. let p1 = Point(3, 4);
    10. let p2 = Point(10, 20);
    11. let p3 = add(&p1, &p2);
    12. println!("&p3.0: {:p}", &p3.0);
    13. println!("{p1:?} + {p2:?} = {p3:?}");
    14. }
  • Rust 编译器能够执行返回值优化 (RVO)。

  • In C++, copy elision has to be defined in the language specification because constructors can have side effects. In Rust, this is not an issue at all. If RVO did not happen, Rust will always perform a simple and efficient memcpy copy.