gpt4 book ai didi

rust - 将非静态生命周期传递给 Rocket 的管理

转载 作者:行者123 更新时间:2023-11-29 07:57:58 25 4
gpt4 key购买 nike

如何将具有非静态生命周期的对象传递给 Rocket 的 manage?目前我有一些类似的东西:

fn foo<'a>(bar: Bar<'a>) -> Result<(), Error> {
rocket::ignite()
.manage(bar)
.mount("/", routes![index])
.launch();

Ok(())
}

但是我得到以下错误:

cannot infer an appropriate lifetime due to conflicting requirements

note: ...so that the expression is assignable:
expected bar::Bar<'_>
found bar::Bar<'a>
note: but, the lifetime must be valid for the static lifetime...

为了添加更多上下文,Bar 是一个包含盒装闭包的 struct,这些闭包使用运行时参数进行初始化。 args 包含密码、 key 和 secret 等内容 - 实际代码是开源的,因此可以找到 here .它是 WIP,因此会发生变化,并不完全是最新的,但希望能为最终目标提供一个想法。

最佳答案

您不能使用非静态生命周期,因为 manage() 的签名字面意思是 Send + Sync + 'static .其原因在 documentation for State 中说明。 :

The type being managed must be thread safe and sendable across thread boundaries. In other words, it must implement Send + Sync + 'static.

也就是说,由于(工作)线程可以随时访问托管状态,并且由于无法保证这些线程何时退出,因此托管状态必须至少与整个程序一样长;那是'static .

您可以尝试更改您的 foo()采取bar: Bar<'static>而不是通用的生命周期,然后从那里开始工作。 'static 的要求通常并不像听起来那么糟糕,因为所有拥有的值(如 String::new() )都是 'static只要它们不包含对其他事物的引用。

如果您无法提供 Bar<'static> , 你也许可以使用 Arc而不是普通引用所以 Bar<'a>变成 Bar .这里的基本原理是 Bar持有原子计数的引用而不是引用,所以持有 Bar保证所有成员都活着 Bar活着。这使得 Bar 'static .


作为旁注:在考虑 'static 时可能会有所帮助某些类型的要求是 'static 是否意味着该值实际上永远存在。这只是意味着值(value)可以永远存在。在你的例子中,State无法强制其他线程退出并销毁它们的值。因此 State必须保证它所操作的所有值都可以与 State 一样长地存在。想要。仅当这些值为 'static 时才成立。在线程边界。

关于rust - 将非静态生命周期传递给 Rocket 的管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55924379/

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