I want some data object to serialize itself and make a version of itself that is possible to send via UDP. The problem is that the String
created by serialization (serde_json::to_string
) lives only until end of scope (which makes sense to me) so the byte version (a &[u8]
from as_bytes
) cannot reference it out of scope. I've tried adding some lifetime parameters but without success; I don't actually understand lifetime parameters that much yet.
#[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 | | }
| |_____^