此问题已经在这里有了答案:
这个问题可能很简单,但是我还没有找到关于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
}
Dummy {}
是常数,因此可以具有静态寿命。如果您尝试返回对其的可变引用,或者结果不是恒定的,则将无法使用。
struct Dummy {
foo: u32,
}
// nope
fn dummy_ref<'a>(foo: u32) -> &'a Dummy {
&Dummy { foo }
}