I am trying to learn Rust, and while doing so I wanted to try converting a struct object to a byte array, but I am running into issues doing so.
So I have this:
struct Node<'a> { id: u8, name: &'a str, data: &'a str, } impl<'a> Node<'a> { fn new() -> Node<'a> { return Node { id: 1, name: "superName", data: "some random desc2", }; } fn to_buffer(&mut self) -> &'a [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 &[self.id]; } } but I am just getting the error "cannot return reference to temporary value" And I am not 100% sure that I understand the error message to begin with... is it because self.id is only scoped to this function and would be removed from the stack when it is returned?
And is there any way around this?
[self.id]creates an array on the stack,&[self.id]refers to this array, but since this array was created inside a function block, it's dropped right when you exitto_bufferfunction block. Compiler complains that you try to return a reference on the dropped array