这个问题可能微不足道,但是我还没有找到关于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
}