[英]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
”。 現在'a
是Test
本身的生命,所以我想(我認為) where 'Self: 'a
(所以self
生活至少和'a
一樣長)。 我似乎無法想出這個Index
impl? 我嘗試將PhantomData
添加到我的Test
。 但我沒有到達任何地方。 有什么建議?
正如評論中指出的那樣,您將無法完全按照自己的意願行事。 但是,你真正想要的是復制HashMap
的get
方法。 因此,我建議您自己編寫或者使用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 }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.