我有一个Vec<u8>
,我想多次进行一些操作。我会用Arc
。这是MVCE:
use futures::executor::{block_on, ThreadPool};
use futures::task::SpawnExt;
use std::pin::*;
use std::sync::Arc;
fn foo(b: Arc<Vec<u8>>) {
println!("{:?}", b);
}
#[test]
fn pin_test() {
let v = Arc::new(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let mut pool = ThreadPool::new().unwrap();
for _ in 0..10 {
let v1 = v.clone();
let handle = pool
.spawn_with_handle(async {
foo(v1);
})
.unwrap();
block_on(handle);
}
}
我原本希望能够Pin
代替Vec<u8>
use futures::executor::{block_on, ThreadPool};
use futures::task::SpawnExt;
use std::pin::*;
use std::sync::Arc;
fn foo(b: &[u8]) {
println!("{:?}", b);
}
#[test]
fn pin_test() {
let v = Pin::new(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let mut pool = ThreadPool::new().unwrap();
for _ in 0..10 {
let v1 = v.clone();
let handle = pool
.spawn_with_handle(async {
foo(&*v1);
})
.unwrap();
block_on(handle);
}
}
自然会产生错误'argument requires that
v1 is borrowed for 'static
我知道Pin应该将vec数据固定到特定点,这样所有调用都可以引用相同的数据。什么是使用Pin的正确方法,以便我可以将引用传递给foo()
包装:期货0.3Rust 1.39稳定
缺少move
。
更改
let handle = pool
.spawn_with_handle(**async** {
foo(&*v1);
})
.unwrap();
到
let handle = pool
.spawn_with_handle(**async move** {
foo(&*v1);
})
.unwrap();