I'm pretty new to Rust and struggling with the concepts of ownership. In this example, I'm using SIMD Json for Rust library to parse JSON. It has a concept of parsing "borrowed values" - JSON objects referencing the original JSON bytes.
To make this example self-sufficient, let's use these signatures:
// Emulating simd_json::BorrowedValue
pub enum BorrowedValue<'value> {
SomeEnumOption(&'value str)
}
// Emulating simd_json::to_borrowed_value parsing function
pub fn to_value(buf: &mut [u8]) -> Result<BorrowedValue, String> {
todo!()
}
Now I want to make a self-sufficient struct that would carry both the original JSON as well as the parsed structue:
pub struct ParsedJson<'value> {
file_content: Vec<u8>,
pub parsed: BorrowedValue<'value>,
}
However, I fail to create such struct:
fn transform<'value>(mut buf: Vec<u8>) -> Result<ParsedJson<'value>, String> {
let mut result = ParsedJson {
file_content: buf,
parsed: BorrowedValue::SomeEnumOption("nothing here yet"),
};
match to_value(&mut result.file_content) {
Ok(bw) => {
result.parsed = bw;
Ok(result)
}
Err(e) => Err(e)
}
}
This results in an error:
error[E0515]: cannot return value referencing local data `result.file_content`
--> src/json.rs:39:13
|
36 | match to_value(&mut result.file_content) {
| ------------------------ `result.file_content` is borrowed here
...
39 | Ok(result)
| ^^^^^^^^^^ returns a value referencing data owned by the current function
Why is result.file_content
considered local data? I expected I could move it out.
To add to the confusion, it seems to not be considered a local data anymore if I don't pass a mutable reference to to_value
:
fn transform<'value>(mut buf: Vec<u8>) -> Result<ParsedJson<'value>, String> {
let mut result = ParsedJson {
file_content: buf,
parsed: BorrowedValue::SomeEnumOption("nothing here yet"),
};
Ok(result) // This compiles just fine!
}
What is the problem and what is the proper way to implement that? I'm completely lost here, any pointers would be appreciated.