我想要一些数据对象来序列化自己,并制作一个可以通过UDP发送的自身版本。问题是,由序列化(serde_json::to_string)创建的serde_json::to_string只存在到作用域的结束(这对我来说很有意义),因此字节版本(来自as_bytes的&[u8] )不能将其引用到范围之外。我尝试过添加一些终身参数,但没有成功;我还没有真正理解生命参数。
#[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 | | }
| |_____^发布于 2018-02-09 18:00:11
正如你已经计算出的,切片不能超过范围。我不认为您可以用生存期注释来解决这个问题:显式的生命周期实际上不能使对象活得更长,它们只会阻止编译器对哪些生命周期是相同的进行严格的假设。
这样做的方法是将这些字节的所有权还给调用方,而不是将它们借用到一个片段中。最明显的候选是Vec。
pub fn to_utf8(&self) -> Vec<u8> {
Vec::from(serde_json::to_string(&self).unwrap().as_bytes())
}这是一个额外的副本,这是不幸的,但幸运的是,Serde提供了一个函数,可以直接为您提供这个输出!
pub fn to_utf8(&self) -> Vec<u8> {
serde_json::to_vec(&self).unwrap()
} 现在,您可以返回一个Vec<u8>,它将由调用方拥有,并且只要调用方需要就可以使用。您可以完全按照使用切片的方式使用Vec<u8>,如果需要的话,甚至可以从它借用底层的切片。
https://stackoverflow.com/questions/48711176
复制相似问题