首页 > 解决方案 > 什么时候创造临时价值?

问题描述

这个问题可能是微不足道的,但我还没有找到任何关于 rust 临时值的好的文档:

为什么直接返回对新建结构的引用而不是使用 new() 创建结构时没有创建临时值?AFAIK 这两个函数通过创建和返回对新创建的结构实例的引用来做同样的事情。

struct Dummy {}

impl Dummy {
    fn new() -> Self {
        Dummy {}
    }
}

// why does this work and why won't there be a temporary value?
fn dummy_ref<'a>() -> &'a Dummy {
    &Dummy {}
}

// why will there be a temp val in this case?
fn dummy_ref_with_new<'a>() -> &'a Dummy {
    &Dummy::new() // <- this fails
}

标签: rust

解决方案


Dummy {}是恒定的,因此它可以具有静态生命周期。如果您尝试返回对它的可变引用,或者如果结果不是常量,则它将不起作用。

struct Dummy {
    foo: u32,
}

// nope
fn dummy_ref<'a>(foo: u32) -> &'a Dummy {
    &Dummy { foo }
}

推荐阅读