我有以下数据 struct (简化):
use std::collections::HashMap;
pub struct StringCache {
// the hashmap keys point to elements stored in `storage`
// so never outlive this datastructure. the 'static refs are never handed out
table: HashMap<&'static str, usize>,
storage: Vec<Box<str>>,
}
在这里引用的生命周期问题上向Rust撒谎是否合法/defined behaviour?对我来说,这感觉就像违反了类型系统. 这个数据 struct 的公共API是否健全? 为了完整起见,下面是完整的实现:
use std::mem::transmute;
impl StringCache {
pub fn intern(&mut self, entry: &str) -> usize {
if let Some(key) = self.table.get(entry) {
return *key;
}
let idx = self.storage.len();
self.storage.push(entry.to_owned().into_boxed_str());
// we cast our refs to 'static here.
let key = unsafe { transmute::<&str, &'static str>(&self.storage[idx]) };
self.table.insert(key, idx);
idx
}
pub fn lookup(&self, idx: usize) -> &str {
&self.storage[idx]
}
}