0
votes

I'd like to write some code like below

struct SomeData(u8, u8);

impl SomeData {
    fn to_bytes(&self) -> &[u8] {
        let mut bytes: [u8; 16] = [0; 16];

        // fill up buffer with some data in `SomeData`.
        bytes[0] = self.0;
        bytes[1] = self.1;

        // return slice
        &bytes[..]
    }
}

I know the reason why above code doesn't work. How can I return a reference specifying that its lifetime is the same as self?

2
But buffer is a local variable here ? What is the link with self ? Why don't just move the value ? - Stargateur
I know the reason why above code doesn't work — Would you care to share why you think it should work? - Shepmaster
It seems that I didn't understand much about Rust. Thanks all of your answers! - Atsuki Takahashi

2 Answers

4
votes

Explicit lifetime annotation of a reference cannot extend lifetime of an object it refers to. bytes is a local variable and it will be destroyed when function ends.

One option is to return an array

fn to_bytes(&self) -> [u8;16] {
    ...
    // return array
    bytes
}

Another one is to pass mutable slice into function

fn to_bytes(&self, bytes: &mut [u8]) {
    ...
}
4
votes

When you want a function to return a reference:

fn to_bytes(&self) -> &[u8]

It is possible only if that reference points to its argument (in this case self), because it has a longer lifetime than the function. Example (with a slice-friendly SomeData):

struct SomeData([u8; 16]);

impl SomeData {
    fn to_bytes(&self) -> &[u8] {
        &self.0[8..]
    }
}

In your case you are attempting to return a slice of a local variable and since that variable's lifetime ends by the time the to_bytes function returns, the compiler refuses to provide a reference to it.