[英]How can I return a reference to a local variable specifying that its lifetime is the same as self?
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
? 如何返回指定其生存期与
self
相同的引用?
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. bytes
是局部变量,函数结束时将被销毁。
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]) {
...
}
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. 仅当该引用指向其参数(在这种情况下为
self
)时才有可能,因为它的寿命比该函数更长。 Example (with a slice-friendly SomeData
): 示例(具有切片友好的
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. 在您的情况下,您尝试返回一个局部变量的切片,并且由于该变量的生命周期在
to_bytes
函数返回时结束,因此编译器拒绝提供对其的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.