无法构建支持POST请求的Rust Rocket Web服务器
问题
在使用Rust的Rocket框架创建Web服务器时遇到错误,编写的极简代码如下:
#[macro_use] extern crate rocket; use rocket::serde::{Serialize, Deserialize}; use rocket::serde::json::Json; #[derive(Serialize, Deserialize)] #[serde(crate = "rocket::serde")] pub struct PersonEntity { name: &'static str, age: u8, } #[post("/", format = "json", data= "<new_person>")] pub fn add_person(new_person: Json<PersonEntity>) -> Json<PersonEntity> { Json(PersonEntity {name: "peter", age: 33}) } #[launch] fn rocket() -> _ { rocket::build() .mount("/person", routes![ add_person ]) }
出现的错误信息:
error[E0521]: borrowed data escapes outside of function --> src/person/person_controller.rs:10:31 | 9 | #[post("/", format = "json", data= "<new_person>")] | --------------------------------------------------- | | | `__req` is a reference that is only valid in the function body | lifetime `'__r` defined here 10 | pub fn add_person(new_person: Json<PersonEntity>) -> Json<PersonEntity> { | ^^^^ | | | `__req` escapes the function body here | argument requires that `'__r` must outlive `'static`
解决方案
问题出在PersonEntity结构体的name字段类型是&'static str。
Rocket反序列化请求中的JSON数据时,这些数据仅存活于请求的生命周期内(即错误信息中的'__r生命周期),但&'static str要求引用的数据必须存活至程序结束,二者生命周期不匹配,触发编译器报错。
只需将name的类型改为String,让结构体拥有字符串的所有权,即可解决问题:
#[derive(Serialize, Deserialize)] #[serde(crate = "rocket::serde")] pub struct PersonEntity { name: String, age: u8, }
同时调整返回的实例,将字符串字面量转为String:
Json(PersonEntity {name: "peter".to_string(), age: 33})
修改后结构体不再依赖静态生命周期,可正常处理请求中的数据。
内容的提问来源于stack exchange,提问作者Peter Holzer
相关产品推荐
相关产品推荐

