How can I return a reference to a local variable specifying that its lifetime is the same as self?

僤鯓⒐⒋嵵緔 提交于 2019-12-25 09:42:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!