簡體   English   中英

實現Index trait時無約束的生命周期錯誤

[英]Unconstrained lifetime error when implementing Index trait

我有一個擁有HashMap<String, String>

struct Test {
    data: HashMap<String, String>,
}

我正在嘗試為此類型實現Index trait以映射到hashmap的Index實現(涉及其他邏輯,因此我無法公開hashmap)。

如果我只是獲取對hashmap中的值的引用,這是有效的:

impl<'b> Index<&'b str> for Test {
    type Output = String;
    fn index(&self, k: &'b str) -> &String {
        self.data.get(k).unwrap()
    }
}

但是,我希望得到&Option<&String> ,就像data.get() 所以我嘗試了這個:

impl<'b, 'a> Index<&'b str> for Test {
    type Output = Option<&'a String>;
    fn index(&'a self, k: &'b str) -> &Option<&'a String> {
        &self.data.get(k)
    }
}

這導致:

error[E0207]: the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates
 --> <anon>:8:10
  |
8 | impl<'b, 'a> Index<&'b str> for Test {
  |          ^^ unconstrained lifetime parameter

我理解'a的“ unconstrained lifetime parameter ”。 現在'aTest本身的生命,所以我想(我認為) where 'Self: 'a (所以self生活至少和'a一樣長)。 我似乎無法想出這個Index impl? 我嘗試將PhantomData添加到我的Test 但我沒有到達任何地方。 有什么建議?

正如評論中指出的那樣,您將無法完全按照自己的意願行事。 但是,你真正想要的是復制HashMapget方法。 因此,我建議您自己編寫或者使用Deref (而不是 DerefMut )來直接向內部HashMap提供struct的所有者不可變訪問權限。 希望這意味着用戶不會搞亂你的struct的內部邏輯。 請記住,如果同時執行這兩項操作,則Deref將不會用於調用HashMap::get因為Test::get將可用。

struct FooMap {
    data: HashMap<String, String>
}

復制get

impl FooMap {
    pub fn get(&self, index: &str) -> Option<&String> { self.data.get(index) }
}

使用Deref

impl Deref for FooMap {
    type Target = HashMap<String, String>;
    fn deref(&self) -> &Self::Target { &self.data }
}

Rust Playground上的示例代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM