何时创建临时值?

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

与使用new()创建结构相反,为什么直接返回对新建结构的引用时没有创建临时值? AFAIK这两个函数通过创建并返回对新创建的struct实例的引用来实现相同的功能。

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
}
tabby37 回答:何时创建临时值?

Dummy {}是常量,因此可以具有静态生存期。如果您尝试返回对其的可变引用,或者结果不是恒定的,那么它将无法正常工作。

struct Dummy {
    foo: u32,}

// nope
fn dummy_ref<'a>(foo: u32) -> &'a Dummy {
    &Dummy { foo }
}
本文链接:https://www.f2er.com/3169477.html

大家都在问