在实现特征时如何明确指定生命周期?

2024-04-09

鉴于下面的实现,基本上我有一些可以通过 i32 id 字段或字符串字段查找的项目集合。为了能够互换使用,使用了特征“IntoKey”,并且match分派到适当的查找映射;这一切都适合我的定义getMapCollection 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与相关的indexfn 表示查找产生的引用将一直存在,只要包含MapCollection.
  • 或者我只是没有使用正确的语法来指定所需的信息?

(using rustc 1.0.0-nightly (b63cee4a1 2015-02-14 17:01:11 +0000))


您是否打算实施IntoKey在将存储生命周期引用的结构上'a?如果没有,您可以将您的特征及其实现更改为:

trait IntoKey {
    fn into_key<'a>(&'a self) -> Key<'a>;
}

如果您可以使用的话,这是通常推荐的定义样式。如果你不能...

让我们看看这个较小的复制品:

use std::collections::HashMap;
use std::ops::Index;

struct Key<'a>(&'a u8);

trait IntoKey<'a> { //'
    fn into_key(&'a self) -> Key<'a>;
}

struct MapCollection;

impl MapCollection {
    fn get<'a, K>(&self, key: &'a K) -> &u8
        where K: IntoKey<'a> //'
    {
        unimplemented!()
    }
}

impl<'a, K> Index<K> for MapCollection //'
    where K: IntoKey<'a> //'
{
    type Output = u8;

    fn index<'b>(&'b self, k: &K) -> &'b u8 { //'
        self.get(k)
    }
}

fn main() {
}

问题在于get:

fn get<'a, K>(&self, key: &'a K) -> &u8
    where K: IntoKey<'a>

在这里,我们参考一下K那必须活得只要 the Key我们摆脱它。然而,Index 特征并不能保证:

fn index<'b>(&'b self, k: &K) -> &'b u8

您可以通过简单地赋予新的生命周期来解决此问题key:

fn get<'a, 'b, K>(&self, key: &'b K) -> &u8
    where K: IntoKey<'a>

或者更简洁地说:

fn get<'a, K>(&self, key: &K) -> &u8
    where K: IntoKey<'a>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在实现特征时如何明确指定生命周期? 的相关文章

随机推荐