簡體   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