为什么没有示例1编译,因为示例2编译得很好?示例之间的唯一区别在于示例1中value
是函数局部变量,而示例2中value
是函数的参数。
示例1
#![feature(scoped)]
use std::thread;
use std::sync::atomic::{AtomicUsize, Ordering};
pub fn foo<F>() {
let mut join_guards = Vec::new();
let value = AtomicUsize::new(0);
for _ in 0..10 {
join_guards.push(thread::scoped(|| {
value.fetch_add(1, Ordering::SeqCst);
}));
}
}
示例2
#![feature(scoped)]
use std::thread;
use std::sync::atomic::{AtomicUsize, Ordering};
pub fn foo<F>(value: AtomicUsize) {
let mut join_guards = Vec::new();
for _ in 0..10 {
join_guards.push(thread::scoped(|| {
value.fetch_add(1, Ordering::SeqCst);
}));
}
}
这些是我尝试编译示例1的错误消息:
error: `value` does not live long enough
join_guards.push(thread::scoped(|| {
value.fetch_add(1, Ordering::SeqCst);
}));
note: reference must be valid for the block at 6:20...
pub fn foo<F>() {
let mut join_guards = Vec::new();
let value = AtomicUsize::new(0);
for _ in 0..10 {
join_guards.push(thread::scoped(|| {
note: ...but borrowed value is only valid for the block suffix following statement 1 at 8:40
let value = AtomicUsize::new(0);
for _ in 0..10 {
join_guards.push(thread::scoped(|| {
value.fetch_add(1, Ordering::SeqCst);
}));