gpt4 book ai didi

rust - 没有附加变量的生命周期是什么意思?

转载 作者:行者123 更新时间:2023-12-04 03:31:45 25 4
gpt4 key购买 nike

fn hello<'a>() {}
在 Rust 中,函数可以有自己的生命周期吗?
我遇到了一段代码如下
struct Hi {}

async fn wrapper<'a, F, Fut>(f: F)
where
Fut: Future<Output = ()>,
F: FnOnce(&'a mut Hi) -> Fut{

}

但无法理解 life'a 在这里意味着什么......

最佳答案

can a function have its own lifetime?


函数没有生命周期;引用做。但是你可以引用一个函数。您可以将生命周期作为函数的参数。

couldn't understand what lifetime 'a could mean here.


这只是意味着它是一个可变借用的闭包参数,具有生命周期 &'a .
本质上, async fn wrapper<F, Fut>(f: F)行为相同,因为 &' a可以省略。
如果在函数代码中的某处,您需要说生命周期 'a,那将会很有用。会活得更久 'b .
例如:
async fn wrapper<'a, 'b, F, Fut>(f: F, b: &'b Hi)
where
Fut: Future<Output = ()>,
F: FnOnce(&'a mut Hi) -> Fut,
'a : 'b

关于rust - 没有附加变量的生命周期是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66668270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com