gpt4 book ai didi

rust - 具有结构引用的 Iron 持久状态

转载 作者:行者123 更新时间:2023-11-29 08:31:45 25 4
gpt4 key购买 nike

我正在努力获取与 Iron 一起使用的持久引用,但不确定如何设置合适的生命周期。我希望能够在不同的路线上重复使用 Controller 。

示例:

use iron::prelude::*;
use iron::typemap::Key;
use persistent::Read;
use router::Router;

pub struct Controller;

pub struct Rest {
controller: Controller,
}

impl Key for &Controller {
type Value = Self;
}

impl Rest {
pub fn run(&self) {
let router = Router::new();
let mut chain = Chain::new(router);
chain.link(Read::<&Controller>::both(&self.controller));
Iron::new(chain).http(format!("0.0.0.0:1234")).ok();
}
}

fn main() {
Rest {
controller: Controller,
}
.run();
}
[dependencies]
iron = "0.6.*"
router = "0.6.*"
persistent = "0.4.0"

Gist of example

error[E0478]: lifetime bound not satisfied
--> src/main.rs:12:6
|
12 | impl Key for &Controller {
| ^^^
|
note: lifetime parameter instantiated with the lifetime '_ as defined on the impl at 12:14
--> src/main.rs:12:14
|
12 | impl Key for &Controller {
| ^
= note: but lifetime parameter must outlive the static lifetime

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'_` due to conflicting requirements
--> src/main.rs:12:6
|
12 | impl Key for &Controller {
| ^^^
|
note: first, the lifetime cannot outlive the lifetime '_ as defined on the impl at 12:14...
--> src/main.rs:12:14
|
12 | impl Key for &Controller {
| ^
= note: ...so that the types are compatible:
expected typemap::Key
found typemap::Key
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `&Controller` will meet its required lifetime bounds
--> src/main.rs:12:6
|
12 | impl Key for &Controller {
| ^^^

最佳答案

如错误消息所述:

but lifetime parameter must outlive the static lifetime

这是因为Key使用 Any作为超特征,它需要 'static:

pub trait Any: 'static {
fn type_id(&self) -> TypeId;
}

最简单的解决方案是为一个值实现Key,然后将该值赋给Read::both:

impl Key for Controller {
type Value = Self;
}

impl Rest {
pub fn run(self) {
let router = Router::new();
let mut chain = Chain::new(router);
chain.link(Read::<Controller>::both(self.controller));
Iron::new(chain).http(format!("0.0.0.0:1234")).ok();
}
}

I want the persistent data to be globally shared across all of these routes

在那种情况下,我会完全避免使用持久性箱子,而只创建一个单例:

关于rust - 具有结构引用的 Iron 持久状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55997427/

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