繁体   English   中英

为什么 Index trait 允许返回对临时值的引用?

[英]Why does the Index trait allow returning a reference to a temporary value?

考虑这个简单的代码

use std::ops::Index;
use std::collections::HashMap;

enum BuildingType {
    Shop,
    House,
}

struct Street {
    buildings: HashMap<u32, BuildingType>,
}

impl Index<u32> for Street {
    type Output = BuildingType;

    fn index(&self, pos: u32) -> &Self::Output {
        &self.buildings[&pos]
    }
}

它编译没有问题,但我不明白为什么借用检查器没有抱怨返回对index function 中临时值的引用。

为什么它有效?

你的例子看起来不错。

Index trait 只能“查看” object 中的内容,并且不能用于返回任意动态生成的数据。

在 Rust 中不可能返回对在 function 中创建的值的引用,如果该值没有永久存储在某处(引用本身不存在,它们总是借用某处拥有的一些值)。

不能从 function 中的变量借用引用,因为在 function 返回之前,所有变量都将被销毁。 Lifetimes 仅描述程序的作用,不能“使”某些东西比它已经存在的寿命更长。

fn index(&self) -> &u32 {
   let tmp = 1;
   &tmp  // not valid, because tmp isn't stored anywhere
}
fn index(&self) -> &u32 {
   // ok, because the value is stored in self,
   // which existed before this function has been called
   &self.tmp 
}

您可能会发现返回&1有效。 那是因为1存储在程序的可执行文件中,就程序而言,它是永久存储。 但是'static是文字的一个例外,并且泄漏了 memory,所以在大多数情况下,它不是你可以依赖的东西。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM