为什么 "capture by reference" 等同于 Rust 中的 "capture a reference by value"?
Why is "capture by reference" equivalent to "capture a reference by value" in Rust?
摘自 Huon Wilson 的Finding Closure in Rust:
Capturing entirely by value is also strictly more general than capturing by reference: the reference types are first-class in Rust, so "capture by reference" is the same as "capture a reference by value". Thus, unlike C++, there’s little fundamental distinction between capture by reference and by value, and the analysis Rust does is not actually necessary: it just makes programmers’ lives easier.
我很难理解这个问题。如果您“按值”捕获引用,那么您是否捕获存储在堆上的数据?还是指向引用的指针值,在栈中找到?
我觉得文章的意思是说效果差不多。 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;
}
Or does it refer to the pointer value of the reference, which is found on the stack?
是的,是的。
在 Rust 中,引用是具体化的,它们是您实际操作的东西。因此,当您按值捕获引用时,您捕获的是引用本身(指针,这是 Rust 引用的真正含义),而不是裁判(指针)。
通过引用捕获基本上只是隐式创建一个引用并按值捕获它。
摘自 Huon Wilson 的Finding Closure in Rust:
Capturing entirely by value is also strictly more general than capturing by reference: the reference types are first-class in Rust, so "capture by reference" is the same as "capture a reference by value". Thus, unlike C++, there’s little fundamental distinction between capture by reference and by value, and the analysis Rust does is not actually necessary: it just makes programmers’ lives easier.
我很难理解这个问题。如果您“按值”捕获引用,那么您是否捕获存储在堆上的数据?还是指向引用的指针值,在栈中找到?
我觉得文章的意思是说效果差不多。 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;
}
Or does it refer to the pointer value of the reference, which is found on the stack?
是的,是的。
在 Rust 中,引用是具体化的,它们是您实际操作的东西。因此,当您按值捕获引用时,您捕获的是引用本身(指针,这是 Rust 引用的真正含义),而不是裁判(指针)。
通过引用捕获基本上只是隐式创建一个引用并按值捕获它。