Anything starting with &
in Rust is a reference to a value, rather than a value itself. A &[u8]
is a reference to a value which needs to exist elsewhere.
Because you create the value it’s a reference to within the function, when the function returns, the value the reference points to no longer exists. (id
still exists, but the slice containing id
does not).
Instead, you can return an owned value, rather than a reference to one:
fn to_buffer(&mut self) -> Vec<u8> {
let mut size = mem::size_of::<Node>();
size = size + self.name.len() * mem::size_of::<char>();
size = size + self.data.len() * mem::size_of::<char>();
println!("size {}", size);
return vec![self.id];
}
which the caller can then take a reference of if that’s what they need.