【发布时间】:2026-01-22 11:35:01
【问题描述】:
我想将预编译的 json 模式传递给 actix web,但编译器抱怨用于创建 JSONSchema 的借用 Value 寿命不够长。有没有办法解决这个问题?
例子:
use jsonschema::JSONSchema;
use serde_json::from_str;
use actix_web::{web, get, App, HttpServer, HttpResponse, Responder};
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
let schema_str = include_str!("schema.json");
let schema_value = from_str(schema_str).unwrap();
let schema_compiled = JSONSchema::compile(&schema_value).unwrap();
App::new()
.data(schema_compiled) // fixme: compiles if commented out
.service(index)
})
.bind("0.0.0.0:8080")?
.run()
.await
}
#[get("/")]
async fn index<'a>(_schema: web::Data<JSONSchema<'a>>) -> impl Responder {
HttpResponse::Ok().finish() // todo: use schema for something
}
来自 rustc 的错误:
error[E0597]: `schema_value` does not live long enough
--> src/main.rs:10:51
|
10 | let schema_compiled = JSONSchema::compile(&schema_value).unwrap();
| --------------------^^^^^^^^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `schema_value` is borrowed for `'static`
...
14 | })
| - `schema_value` dropped here while still borrowed
我是 rust 新手,如果这是一个伪装的通用 rust 问题,我深表歉意(一旦我的理解有所提高,我很乐意用更小的可重复性修改问题)。
【问题讨论】:
-
我认为您可能会将
&' static T与T: 'staticwhich are not the same thing 混淆。 -
我建议您添加
#![deny(rust_2018_idioms)]— 这有助于澄清问题吗? -
感谢大家的澄清和建议。我会继续阅读/调整并报告。
-
抱歉耽搁了@NjugunaMureithi。我刚刚添加了我的答案。我希望它对你有用。干杯,马特。
标签: rust jsonschema actix-web serde-json