【问题标题】:Why is "capture by reference" equivalent to "capture a reference by value" in Rust?为什么“按引用捕获”等同于 Rust 中的“按值捕获引用”?
【发布时间】:2021-03-18 16:04:34
【问题描述】:

摘自 Huon Wilson 的Finding Closure in Rust

完全按值捕获也比按引用捕获更一般:引用类型在 Rust 中是一等的,因此“按引用捕获”与“按值捕获引用”相同。因此,与 C++ 不同,按引用捕获和按值捕获之间几乎没有根本区别,而且 Rust 所做的分析实际上并不是必需的:它只是让程序员的生活更轻松。

我很难理解这一点。如果您“按值”捕获引用,您不会捕获存储在堆上的数据吗?还是引用了引用的指针值,在栈上找到?

【问题讨论】:

    标签: memory rust closures pass-by-reference pass-by-value


    【解决方案1】:

    或者说是引用的指针值,是在栈上找到的?

    是的,是的。

    在 Rust 中,引用是具体化的,它们是您操纵的实际事物。因此,当您按值捕获引用时,您捕获的是引用本身(指针,这就是 Rust 引用的真正含义),而不是裁判(指针)。

    按引用捕获基本上只是隐式创建一个引用并按值捕获它。

    【讨论】:

      【解决方案2】:

      我认为文章的意思是说效果几乎相同。 Immutable references implement Copy trait 因此,当您按值捕获引用时,它会被复制。所以基本上你只是创建了一个对相同数据的共享引用。

      fn as_ref(_x: &String) {}
      
      fn as_mut(_x: &mut String) {}
      
      fn main() {
          let mut x = String::from("hello world");
          let y = &x;
      
          let _ = move || {
              as_ref(y); // here you moved y but it
                         // basically created a copy
          };
      
          let z = y; // can be used later
      
          // The same cannot be done by mutable
          // refs because they don't
          // implement Copy trait
          
          let y = &mut x;
      
          let _ = move || {
              as_mut(y); // here you moved y and
                         // it cannot be used outside
          };
      
          // ERROR! Cannot be used again
          //let z = y;
      }
      

      Playground

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-21
        • 1970-01-01
        • 2016-02-18
        • 1970-01-01
        • 2011-01-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多