I've got code somewhat like the following, which attempts to read from a websocket, parse the JSON result into a struct, and push that struct onto a Vec
buffer.
(我有类似以下代码的代码,该代码尝试从websocket读取,将JSON结果解析为结构,然后将该结构推入Vec
缓冲区。)
The code however fails to compile, because the struct has a lifetime, and the borrow checker complains that the JSON string does not live long enough. (但是,代码无法编译,因为该结构具有生存期,并且借用检查器抱怨JSON字符串的生存期不够长。)
use serde::{Deserialize, Serialize};
use tungstenite::client::AutoStream;
use tungstenite::protocol::WebSocket;
#[derive(Serialize, Deserialize, Debug, Clone)]
struct MyType<'a> {
id: &'a str,
count: i64,
}
fn example<'a>(
conn: &mut WebSocket<AutoStream>,
buff: &'a mut Vec<MyType<'a>>,
) -> Option<Box<dyn std::error::Error>> {
match conn.read_message() {
Err(err) => Some(err.into()),
Ok(msg) => {
let resp_raw = msg.to_string();
let resp_parsed: Result<MyType<'a>, _> = serde_json::from_str(&resp_raw);
match resp_parsed {
Err(err) => Some(err.into()),
Ok(resp) => {
buff.push(resp.clone());
None
}
}
}
}
}
The exact error is that borrowed value [&resp_raw] does not live long enough
.
(确切的错误是borrowed value [&resp_raw] does not live long enough
。)
I'm wondering how I should restructure this code to satisfy the borrow checker;
(我想知道如何重组此代码以满足借阅检查器;)
what is the correct way to push a struct with a lifetime onto the Vec
param? (将具有生命周期的结构推入Vec
参数的正确方法是什么?)
Or is it the case that the &'a str
parsed into MyType
actually still retains a reference to the original JSON string, so there's no way to safely do this?
(还是被解析为MyType
的&'a str
实际上仍然保留了对原始JSON字符串的引用,因此没有办法安全地做到这一点?)
ask by LogicChains translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…