实现Index trait时无约束的生命周期错误

时间:2016-12-23 00:53:16

标签: rust

我有一个拥有struct Test { data: HashMap<String, String>, }

的结构
Index

我正在尝试为此类型实现Index特征以映射到hashmap的impl<'b> Index<&'b str> for Test { type Output = String; fn index(&self, k: &'b str) -> &String { self.data.get(k).unwrap() } } 实现(涉及其他逻辑,因此我无法公开hashmap)。

如果我刚刚获得对hashmap中的值的引用,这是有效的:

&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

这导致:

unconstrained lifetime parameter

我理解“'a中的'a”。现在Testwhere 'Self: 'a本身的生命周期,所以我想(我认为)self(所以'a至少和Index一样长。我似乎无法想象PhantomData impl?我尝试了一些将Test添加到android:scaleType="fitCenter" 的内容。但我没有到达任何地方。有什么建议?

1 个答案:

答案 0 :(得分:1)

正如评论中指出的那样,你将无法完全按照自己的意愿行事。但是,您真正想要的是复制HashMap的{​​{1}}方法。所以我建议你自己写一下,或者推荐get(和 Deref)来给结构的所有者不可变的直接访问内部DerefMut。希望这意味着用户不会搞乱你的struct的内部逻辑。请注意,如果同时执行这两项操作,则HashMap将不会用于调用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

Example code on Rust Playground

相关问题