我怎样才能返回盒装值?

dra*_*tis 4 heap rust

我基本上有一个函数可以创建一些需要在堆上分配的对象。我想要做的是从该函数返回一个包含对该堆分配值的引用的结构。

struct Cont<'a> {
    pub v: &'a i32
}

impl<'a> Cont<'a> {
    fn new(v: &'a i32) -> Cont {
        Cont {
            v: v
        }
    }
}

fn f<'a>() -> Cont<'a> {
    let v = Box::new(6);

    Cont::new(&v)
}

fn main() {
    let c = f();

    println!("{}", c.v);
}
Run Code Online (Sandbox Code Playgroud)

我得到error: 'v' does not live long enough

您可以在此处找到示例。

Fra*_*gné 7

你不能返回一个只包含一个借用的指向你的对象的指针的结构,因为你的对象Box会在函数结束时被销毁。

您需要将 的所有权转移Box到函数之外,以便堆分配的对象保持活动状态。最简单的方法是将 移动Box到您的结构中:

struct Cont {
    pub v: Box<i32>
}

impl Cont {
    fn new(v: Box<i32>) -> Cont {
        Cont {
            v: v
        }
    }
}

fn f() -> Cont {
    let v = Box::new(6);
    Cont::new(v)
}

fn main() {
    let c = f();

    println!("{}", c.v);
}
Run Code Online (Sandbox Code Playgroud)

如果您想要一个能够存储借用指针或拥有Box(或其他类型的智能指针)的结构,我们可以使其成为Borrowtrait 的泛型。

use std::borrow::Borrow;

struct Cont<T> where T: Borrow<i32> {
    pub v: T
}

impl<T> Cont<T> where T: Borrow<i32> {
    fn new(v: T) -> Cont<T> {
        Cont {
            v: v
        }
    }
}

fn owned() -> Cont<Box<i32>> {
    let v = Box::new(6);
    Cont::new(v)
}

fn borrowed(v: &i32) -> Cont<&i32> {
    Cont::new(v)
}

fn main() {
    let c = owned();
    println!("{}", c.v);

    let x = 123;
    let c = borrowed(&x);
    println!("{}", c.v);
}
Run Code Online (Sandbox Code Playgroud)