How can I do something like that:
struct Parsed<'a> {
bytes: Vec<u8>,
h: &'a [u8]
}
impl<'a> Parsed<'a> {
fn new(bytes: Vec<u8>) -> Self {
let h = bytes.as_slice();
Parsed {
bytes,
h,
}
}
}
I need it for parsing messages with nom from tcp streams without copy objects. Cause I know size of messages, I can prepare some byte array for nom, but cannot return parsed messages to caller. I think it's a good idea to place buffer inside message struct, but it fail with rust borrow-checker :'(
Borrow checker says as follows:
error[E0515]: cannot return value referencing function parameter `bytes`
--> src/main.rs:217:13
|
216 | let h = bytes.as_slice();
| ----- `bytes` is borrowed here
217 | / Parsed {
218 | | bytes,
219 | | h,
220 | | }
| |_____________^ returns a value referencing data owned by the current function
error[E0505]: cannot move out of `bytes` because it is borrowed
--> src/main.rs:218:17
|
214 | impl<'a> Parsed<'a> {
| -- lifetime `'a` defined here
215 | fn new(bytes: Vec<u8>) -> Self {
216 | let h = bytes.as_slice();
| ----- borrow of `bytes` occurs here
217 | / Parsed {
218 | | bytes,
| | ^^^^^ move out of `bytes` occurs here
219 | | h,
220 | | }
| |_____________- returning this value requires that `bytes` is borrowed for `'a`