I want to use the midly crate for standard MIDI file (SMF) parsing. The parse function I want to call has this signature:
pub fn parse(raw: &[u8]) -> Result<Smf>
When I try this
pub fn read0(path: &str) -> Smf {
let data = fs::read(path).unwrap(); // a Vec<u8>
Smf::parse(&data).unwrap()
}
I get the error
34 | Smf::parse(&data).unwrap()
| ^^^^^^^^^^^-----^^^^^^^^^^
| | |
| | `data` is borrowed here
| returns a value referencing data owned by the current function
So the idea is to return both the data buffer and the parsed Smf together:
pub struct Ret2<'a> {
data: Vec<u8>,
smf: Smf<'a>,
}
pub fn read2(path: &str) -> Ret2 {
let data = fs::read(path).unwrap();
let smf = Smf::parse(&data).unwrap();
Ret2 {data, smf}
}
But this does not work, since the compiler seems not to understand that both are returned together and complains about every item individually:
error[E0515]: cannot return value referencing local variable `data`
--> src/bin/../midifile.rs:57:5
|
56 | let smf = Smf::parse(&data).unwrap();
| ----- `data` is borrowed here
57 | Ret2 {data, smf}
| ^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
error[E0505]: cannot move out of `data` because it is borrowed
--> src/bin/../midifile.rs:57:11
|
54 | pub fn read2(path: &str) -> Ret2 {
| - let's call the lifetime of this reference `'1`
55 | let data = fs::read(path).unwrap();
56 | let smf = Smf::parse(&data).unwrap();
| ----- borrow of `data` occurs here
57 | Ret2 {data, smf}
| ------^^^^------
| | |
| | move out of `data` occurs here
| returning this value requires that `data` is borrowed for `'1`
How must this be done in Rust?