我试图理解如何将HashMap中的值类型从&'t str
更改为Value<'t>(&'t str)
,从而对下面传递给get
的Key
类型提出更严格的要求.
#![allow(dead_code, unused)]
use std::collections::HashMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Key<'t>(&'t str);
#[derive(Debug, Clone, Copy)]
struct Value<'t>(&'t str);
#[derive(Debug)]
struct Map1<'t>(HashMap<Key<'t>, &'t str>);
#[derive(Debug)]
struct Map2<'t>(HashMap<Key<'t>, Value<'t>>);
impl<'t> Map1<'t> {
fn get<'map>(&'map self, key: &Key<'_>) -> Option<&'map str> {
self.0.get(key).map(|x| *x)
}
}
impl<'t> Map2<'t> {
fn get<'map>(&'map self, key: &Key<'_>) -> Option<&'map Value<'t>> {
// Doesn't work, says: -------- help: add explicit lifetime `'map` to the type of `key`: `&Key<'map>`
self.0.get(key)
}
}
在值类型为&'t str
的Map1
中,可以传入具有任意生存期的Key
,而在值类型为Value<'t>
(&'t str
左右的新类型包装器)的Map2
中,这就不再合适了,我应该传递一个其内部生存期与映射本身一样长的键.
你能帮我了解一下为什么会这样吗?
我能做些什么来使新型的包装Value(&str)
和&str
一样工作吗?