[英]Unconstrained lifetime error when implementing Index trait
I have a struct that owns a HashMap<String, String>
, 我有一个拥有HashMap<String, String>
,
struct Test {
data: HashMap<String, String>,
}
I am trying to implement the Index
trait for this type to map to the Index
implementation of the hashmap (there's other logic involved so I cannot expose the hashmap). 我正在尝试为此类型实现Index
trait以映射到hashmap的Index
实现(涉及其他逻辑,因此我无法公开hashmap)。
This works if I am just getting a reference to the value in the hashmap: 如果我只是获取对hashmap中的值的引用,这是有效的:
impl<'b> Index<&'b str> for Test {
type Output = String;
fn index(&self, k: &'b str) -> &String {
self.data.get(k).unwrap()
}
}
However, I want to get &Option<&String>
out of it, like data.get()
. 但是,我希望得到&Option<&String>
,就像data.get()
。 So I tried this: 所以我尝试了这个:
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)
}
}
This results in: 这导致:
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
I understand the " unconstrained lifetime parameter
in 'a
". 我理解'a
的“ unconstrained lifetime parameter
”。 Now 'a
is the lifetime of Test
itself, so I want (I think) where 'Self: 'a
(so self
lives at least as long as 'a
) . 现在'a
是Test
本身的生命,所以我想(我认为) where 'Self: 'a
(所以self
生活至少和'a
一样长)。 I cannot seem to figure this out for Index
impl? 我似乎无法想出这个Index
impl? I tried some things with adding PhantomData
to my Test
. 我尝试将PhantomData
添加到我的Test
。 But I am not getting anywhere. 但我没有到达任何地方。 Any suggestions? 有什么建议?
As has been pointed out in the comments, you won't be able to do exactly what you want. 正如评论中指出的那样,您将无法完全按照自己的意愿行事。 But, what it seems like you really want is to replicate HashMap
's get
method. 但是,你真正想要的是复制HashMap
的get
方法。 So I would suggest either writing your own, or implmenting Deref
(and not DerefMut
) to give the struct's owner immutable access directly to the internal HashMap
. 因此,我建议您自己编写或者使用Deref
(而不是 DerefMut
)来直接向内部HashMap
提供struct的所有者不可变访问权限。 Hopefully that means the user can't mess up your struct's internal logic. 希望这意味着用户不会搞乱你的struct的内部逻辑。 Keep in mind that if you do both then Deref
will not be used to called HashMap::get
because Test::get
will be available. 请记住,如果同时执行这两项操作,则Deref
将不会用于调用HashMap::get
因为Test::get
将可用。
struct FooMap {
data: HashMap<String, String>
}
Replicating get
: 复制get
:
impl FooMap {
pub fn get(&self, index: &str) -> Option<&String> { self.data.get(index) }
}
Using Deref
: 使用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.