[英]How to use use Pin rather than Arc to pass a Vec<u8> by reference to an async block?
I want to do an operation on a Vec<u8>
multiple times using an Arc
:我想使用Arc
对Vec<u8>
进行多次操作:
use futures::{
executor::{block_on, ThreadPool},
task::SpawnExt,
}; // 0.3.4
use std::{pin::*, 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);
}
}
I was expecting to be able to Pin
the Vec<u8>
instead我希望能够改为Pin
Vec<u8>
use futures::{
executor::{block_on, ThreadPool},
task::SpawnExt,
}; // 0.3.4
use std::{pin::*, 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);
}
}
This gives the error:这给出了错误:
error[E0597]: `v1` does not live long enough
--> src/lib.rs:19:23
|
18 | .spawn_with_handle(async {
| ________________________________-_____-
| |________________________________|
| ||
19 | || foo(&*v1);
| || ^^ borrowed value does not live long enough
20 | || })
| || -
| ||_____________|
| |______________value captured here by generator
| argument requires that `v1` is borrowed for `'static`
...
23 | }
| - `v1` dropped here while still borrowed
I understood that Pin
should pin the Vec
data to a specific point, such that all the calls could reference the same data.我知道Pin
应该将Vec
数据固定到特定点,以便所有调用都可以引用相同的数据。 What is the right way to use Pin
so that I can pass a reference to foo()
?使用Pin
以便我可以传递对foo()
的引用的正确方法是什么?
I'm using Rust 1.39.我正在使用 Rust 1.39。
You are missing a move
.你错过了一个move
。
Change改变
let handle = pool
.spawn_with_handle(async {
foo(&*v1);
})
.unwrap();
to至
let handle = pool
.spawn_with_handle(async move {
// ^^^^
foo(&*v1);
})
.unwrap();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.