鉴于下面的实现,基本上我有一些可以通过 i32 id 字段或字符串字段查找的项目集合。为了能够互换使用,使用了特征“IntoKey”,并且match
分派到适当的查找映射;这一切都适合我的定义get
内MapCollection
impl:
use std::collections::HashMap;
use std::ops::Index;
enum Key<'a> {
I32Key(&'a i32),
StringKey(&'a String),
}
trait IntoKey<'a> {
fn into_key(&'a self) -> Key<'a>;
}
impl<'a> IntoKey<'a> for i32 {
fn into_key(&'a self) -> Key<'a> { Key::I32Key(self) }
}
impl<'a> IntoKey<'a> for String {
fn into_key(&'a self) -> Key<'a> { Key::StringKey(self) }
}
#[derive(Debug)]
struct Bar {
i: i32,
n: String,
}
struct MapCollection
{
items: Vec<Bar>,
id_map: HashMap<i32, usize>,
name_map: HashMap<String, usize>,
}
impl MapCollection {
fn new(items: Vec<Bar>) -> MapCollection {
let mut is = HashMap::new();
let mut ns = HashMap::new();
for (idx, item) in items.iter().enumerate() {
is.insert(item.i, idx);
ns.insert(item.n.clone(), idx);
}
MapCollection {
items: items,
id_map: is,
name_map: ns,
}
}
fn get<'a, K>(&self, key: &'a K) -> Option<&Bar>
where K: IntoKey<'a> //'
{
match key.into_key() {
Key::I32Key(i) => self.id_map.get(i).and_then(|idx| self.items.get(*idx)),
Key::StringKey(s) => self.name_map.get(s).and_then(|idx| self.items.get(*idx)),
}
}
}
fn main() {
let bars = vec![Bar { i:1, n:"foo".to_string() }, Bar { i:2, n:"far".to_string() }];
let map = MapCollection::new(bars);
if let Some(bar) = map.get(&1) {
println!("{:?}", bar);
}
if map.get(&3).is_none() {
println!("no item numbered 3");
}
if let Some(bar) = map.get(&"far".to_string()) {
println!("{:?}", bar);
}
if map.get(&"baz".to_string()).is_none() {
println!("no item named baz");
}
}
但是,如果我想实施std::ops::Index
对于这个结构,如果我尝试执行以下操作:
impl<'a, K> Index<K> for MapCollection
where K: IntoKey<'a> {
type Output = Bar;
fn index<'b>(&'b self, k: &K) -> &'b Bar {
self.get(k).expect("no element")
}
}
我遇到了编译器错误:
src/main.rs:70:18: 70:19 error: cannot infer an appropriate lifetime for automatic coercion due to conflicting requirements
src/main.rs:70 self.get(k).expect("no element")
^
src/main.rs:69:5: 71:6 help: consider using an explicit lifetime parameter as shown: fn index<'b>(&'b self, k: &'a K) -> &'b Bar
src/main.rs:69 fn index<'b>(&'b self, k: &K) -> &'b Bar {
src/main.rs:70 self.get(k).expect("no element")
src/main.rs:71 }
我找不到办法在这里指定一个不同的生命周期;不允许遵循编译器的建议,因为它更改了函数签名并且不再匹配该特征,并且我尝试的其他任何内容都无法满足生命周期规范。
我知道我可以单独实现每种情况(i32,String)的特征,而不是尝试为 IntoKey 实现一次,但我更一般地尝试理解生命周期和适当的用法。本质上:
- 编译器实际上正在防止出现问题吗?这种做法有什么不妥之处吗?
- 我是否错误地指定了我的生命周期?对我来说,一生
'a
在 Key/IntoKey 中规定引用仅需要足够长的时间来进行查找;一生'b
与相关的index
fn 表示查找产生的引用将一直存在,只要包含MapCollection
.
- 或者我只是没有使用正确的语法来指定所需的信息?
(using rustc 1.0.0-nightly (b63cee4a1 2015-02-14 17:01:11 +0000)
)