rust - 什么时候创造临时价值?
问题描述
这个问题可能是微不足道的,但我还没有找到任何关于 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
}
解决方案
Dummy {}
是恒定的,因此它可以具有静态生命周期。如果您尝试返回对它的可变引用,或者如果结果不是常量,则它将不起作用。
struct Dummy {
foo: u32,
}
// nope
fn dummy_ref<'a>(foo: u32) -> &'a Dummy {
&Dummy { foo }
}
推荐阅读
- c# - 模型绑定返回 NULL
- python - 将单元格值转换为列标题,如果在 python 中匹配,则用 1 填充
- r - 在 R 中,将 Wide 数据帧转换为 Long,同时保留一些信息
- php - PHP 返回 NULL 使用 Tensorflow 运行 Python 脚本
- python - PKCS11 是否总是以相同的顺序查找对象?
- sql - sql server中如何知道Symmetrickey的值
- visual-studio-2010 - 将所有控件缩放到窗口大小
- android - 无法解析符号“ACCESS_BACKGROUND_LOCATION”
- java - DynamoDB(Java)中基于数字限制和偏移的分页
- azure-devops - 托管在 Gitlab 上的来自 Yaml 的 Azure 管道