google / flatbuffers

FlatBuffers: Memory Efficient Serialization Library
https://flatbuffers.dev/
Apache License 2.0
22.56k stars 3.19k forks source link

Rust: FlatBuffers are impossible to return from functions #8225

Open Nickersoft opened 5 months ago

Nickersoft commented 5 months ago

Hey folks!

Full disclaimer: I'm a bit of a newbie at Rust, but am running up against an issue I've scoured the internet for and can't find a solution that applies to the FlatBuffers library. What I'm trying to do is very simple, which is read data from a file, load it into a FB, and return it in a Result:

fn read_from_path(path: &str) -> Result<DictionaryBuffer, Box<dyn Error>> {
    let contents = read_file(path)?;
    let buf = crate::schema_generated::root_as_dictionary_buffer(&contents)?;

    Ok(buf)
}

However, naturally I receive the error:

cannot return value referencing local variable `contents` returns a value referencing data owned by the current function. 

`contents` is borrowed here.

Makes sense, seeing I'm passing a ref to contents to the FB method. Yet, from what I can tell, the returned buffer should be owned, no? I'm not trying to return a reference to the buffer, which is the root cause of the majority of cases I've seen online.

Anyone have an idea how to work around this, or is it an issue with how FB is being implemented? I noticed all the examples instantiate buffers inside a main method, so I have no reference for how to approach this.