<分区>
我想要一些数据对象将其自身序列化并制作一个可以通过 UDP 发送的版本。问题是序列化创建的 String
(serde_json::to_string
) 只存在到范围结束(这对我来说有意义)所以字节版本(a &[u8]
from as_bytes
) 无法超出范围引用它。我尝试添加一些生命周期参数但没有成功;我实际上还不太了解生命周期参数。
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
use std::str;
#[derive(Debug, Serialize, Deserialize)]
struct Test {
text: String,
}
impl Test {
pub fn new(input: &str) -> Self {
Test {
text: String::from(input),
}
}
pub fn to_utf8(&self) -> &[u8] {
// serde_json::to_string returns Result<String, ...>
// String.as_bytes() returns &[u8]
serde_json::to_string(&self).unwrap().as_bytes()
}
}
fn main() {
let a = Test::new("abc");
println!("{:?}", a.to_utf8());
}
error[E0597]: borrowed value does not live long enough
--> src/main.rs:22:9
|
22 | serde_json::to_string(&self).unwrap().as_bytes()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ does not live long enough
23 | }
| - temporary value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 19:5...
--> src/main.rs:19:5
|
19 | / pub fn to_utf8(&self) -> &[u8] {
20 | | // serde_json::to_string returns Result<String, ...>
21 | | // String.as_bytes() returns &[u8]
22 | | serde_json::to_string(&self).unwrap().as_bytes()
23 | | }
| |_____^