问题
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
?
回答1:
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]) {
...
}
回答2:
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.
来源:https://stackoverflow.com/questions/44643430/how-can-i-return-a-reference-to-a-local-variable-specifying-that-its-lifetime-is