- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个结构 Test
我要实现 std::future::Future
这将进行投票 function
:
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
struct Test;
impl Test {
async fn function(&mut self) {}
}
impl Future for Test {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.function() {
Poll::Pending => Poll::Pending,
Poll::Ready(_) => Poll::Ready(()),
}
}
}
那没有用:
error[E0308]: mismatched types
--> src/lib.rs:17:13
|
10 | async fn function(&mut self) {}
| - the `Output` of this `async fn`'s expected opaque type
...
17 | Poll::Pending => Poll::Pending,
| ^^^^^^^^^^^^^ expected opaque type, found enum `Poll`
|
= note: expected opaque type `impl Future`
found enum `Poll<_>`
error[E0308]: mismatched types
--> src/lib.rs:18:13
|
10 | async fn function(&mut self) {}
| - the `Output` of this `async fn`'s expected opaque type
...
18 | Poll::Ready(_) => Poll::Ready(()),
| ^^^^^^^^^^^^^^ expected opaque type, found enum `Poll`
|
= note: expected opaque type `impl Future`
found enum `Poll<_>`
我明白
function
必须调用一次,返回
Future
必须存储在结构中的某处,然后必须轮询保存的 future 。我试过这个:
struct Test(Option<Box<Pin<dyn Future<Output = ()>>>>);
impl Test {
async fn function(&mut self) {}
fn new() -> Self {
let mut s = Self(None);
s.0 = Some(Box::pin(s.function()));
s
}
}
这也不起作用:
error[E0277]: the size for values of type `(dyn Future<Output = ()> + 'static)` cannot be known at compilation time
--> src/lib.rs:7:13
|
7 | struct Test(Option<Box<Pin<dyn Future<Output = ()>>>>);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `(dyn Future<Output = ()> + 'static)`
我打电话后
function()
我拍了
&mut
Test
的引用,因此我无法更改
Test
变量,因此无法存储返回的
Future
内
Test
.
struct Test<'a>(Option<BoxFuture<'a, ()>>);
impl Test<'_> {
async fn function(&mut self) {
println!("I'm alive!");
}
fn new() -> Self {
let mut s = Self(None);
s.0 = Some(unsafe { &mut *(&mut s as *mut Self) }.function().boxed());
s
}
}
impl Future for Test<'_> {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.0.as_mut().unwrap().poll_unpin(cx)
}
}
我希望有另一种方式。
最佳答案
尽管有时您可能想做与您在这里尝试完成的事情类似的事情,但它们很少见。因此,大多数阅读本文的人,甚至可能是 OP,可能希望进行重组,以便用于单个异步执行的结构状态和数据是不同的对象。
要回答您的问题,是的,这是有可能的。除非你想绝对使用不安全的代码,否则你需要使用 Mutex
和 Arc
.您希望在 async fn
中操作的所有字段必须包裹在 Mutex
中并且函数本身将接受 Arc<Self>
.
但是,我必须强调,这不是一个完美的解决方案,您可能不想这样做。根据您的具体情况,您的解决方案可能会有所不同,但我猜测 OP 在使用 Stream
时试图完成的工作s 可以通过类似于 this gist that I wrote 的东西更好地解决.
use std::{
future::Future,
pin::Pin,
sync::{Arc, Mutex},
};
struct Test {
state: Mutex<Option<Pin<Box<dyn Future<Output = ()>>>>>,
// if available use your async library's Mutex to `.await` locks on `buffer` instead
buffer: Mutex<Vec<u8>>,
}
impl Test {
async fn function(self: Arc<Self>) {
for i in 0..16u8 {
let data: Vec<u8> = vec![i]; // = fs::read(&format("file-{}.txt", i)).await.unwrap();
let mut buflock = self.buffer.lock().unwrap();
buflock.extend_from_slice(&data);
}
}
pub fn new() -> Arc<Self> {
let s = Arc::new(Self {
state: Default::default(),
buffer: Default::default(),
});
{
// start by trying to aquire a lock to the Mutex of the Box
let mut lock = s.state.lock().unwrap();
// create boxed future
let b = Box::pin(s.clone().function());
// insert value into the mutex
*lock = Some(b);
} // block causes the lock to be released
s
}
}
impl Future for Test {
type Output = ();
fn poll(
self: std::pin::Pin<&mut Self>,
ctx: &mut std::task::Context<'_>,
) -> std::task::Poll<<Self as std::future::Future>::Output> {
let mut lock = self.state.lock().unwrap();
let fut: &mut Pin<Box<dyn Future<Output = ()>>> = lock.as_mut().unwrap();
Future::poll(fut.as_mut(), ctx)
}
}
关于asynchronous - 如何实现轮询异步 fn 的 Future 或 Stream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61295176/
这个问题在这里已经有了答案: JavaScript idiom: !something && function() (5 个答案) 关闭 9 年前。 我多次看到 fn && fn() 是对 if (
我在一个对象中有两个函数 var obj = {}; obj.fn1 = function(){ console.log('obj.fn1'); return this; }; obj.fn2 = f
我正在尝试使用以下 cloudformation 堆栈,但我一直失败并出现以下错误: 模板错误:每个 Fn::Split 对象都需要两个参数,(1) 字符串分隔符和 (2) 要拆分的字符串或返回要拆分
请在这方面提供一些帮助,我将不胜感激。不确定这意味着什么,因为这是我第一次使用 node 和 express。我将 express 设置为与 Node 一起使用,并尝试遵循网站 Express.js
我有一段代码接受 fn 作为参数并将其存储在 object 属性中。 var obj = {}; function anotherFn(fn){ obj["name"] = fn.apply(f
谁能解释一下? IE8 ( function(){ window.foo = function foo(){}; console.log( window.foo === foo );
我查看了lazy-seq的来源,我发现了这个: Clojure 1.4.0 user=> (source lazy-seq) (defmacro lazy-seq "Takes a body of
我知道 $fn.insertAfter() 用于在作为参数提供的元素之后插入元素。 $fn.after() 与它有何不同? 最佳答案 $.fn.after()help在您调用的目标元素之后插入一个元素
所以我的网络模板中有这个 CloudFormation 资源: Resources: ... PubSubnetAz2: Type: AWS::EC2::Subnet
有some conventions说到using brackets in JavaScript ,但是当使用方括号调用时,它们实际上会得到不同的对待吗? fn () 是否与 fn() 有任何不同,人类
我正在尝试将 clojurescript 编译为 Nodejs,我只是想使用 println 函数: (println "hello world") 但是,它给了我一个错误 No *print-fn
我在看别人代码的时候,有看到代码是这样写的 function(){ fn&&fn() } 大概意思是这么个意思,但是这我感觉这样写好像没意义,有带佬能指点一下吗
是否可以使用折叠表达式实现以下目的? template auto foo(Args... args) { //calling foo(x0, x1, x2) should be exactly
fn func(_: i64) -> bool { true } fn func_of_func(callback: &fn(i64) -> bool, arg: i64) -> bool {
我一直在到处寻找对此的解释。我知道,在 Javascript 中,您可以使用方括号表示法获取/设置对象的属性,但是当您在括号中使用“+”时会发生什么,如下所示: obj['e'+type+fn] =
我正在尝试根据Fn::GetAZs'集合动态生成资源: AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::LanguageExtensio
新的 React Hooks 功能很酷,但有时会让我感到困惑。特别是,我将此代码包装在 useEffect Hook 中: const compA = ({ num }) => { const [
我看到这个快捷方式作为代码 Kata 的答案给出,但我很难理解下面的示例在做什么。 function func(fn) { return fn.bind.apply(fn, arguments);
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: C++ namespace question 我见过几个没有命名空间的例子。这样做有什么好处?
所以在一个项目中,我找到了可以简化为的代码: export abstract class Logger { private static log(level: LogLevels, ...ar
我是一名优秀的程序员,十分优秀!