如何返回对局部变量的引用

如何返回对局部变量的引用

本文介绍了如何返回对局部变量的引用,以指定其生存期与self相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一些下面的代码

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[..]
    }
}

我知道上述代码无法正常工作的原因.如何返回一个引用,指定其生存期与self相同?

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?

推荐答案

当您希望函数返回引用时:

When you want a function to return a reference:

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

仅当该引用指向其自变量(在本例中为self)时才有可能,因为它的寿命比该函数的寿命长.示例(带有切片友好的SomeData):

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..]
    }
}

在您的情况下,您尝试返回局部变量的一部分,并且由于该变量的生命周期在to_bytes函数返回时结束,因此编译器拒绝提供对其的引用.

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.

这篇关于如何返回对局部变量的引用,以指定其生存期与self相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 06:23