何时创建临时值? [重复]

问题描述 投票:0回答:1

此问题已经在这里有了答案:

这个问题可能很简单,但是我还没有找到关于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
}
rust
1个回答
0
投票

Dummy {}是常数,因此可以具有静态寿命。如果您尝试返回对其的可变引用,或者结果不是恒定的,则将无法使用。

struct Dummy {
    foo: u32,
}

// nope
fn dummy_ref<'a>(foo: u32) -> &'a Dummy {
    &Dummy { foo }
}
© www.soinside.com 2019 - 2024. All rights reserved.