我想写一个可以存储任何东西的简单键/值存储。我开始用一个围绕HashMap
的小包装器:
use std::any::{Any, TypeId};
use std::collections::HashMap;
#[derive(Debug)]
struct Pair<'a> {
key: &'a str,
value: Box<Any>,
data_type: TypeId,
}
impl<'a> Pair<'a> {
fn new<T>(k: &'a str, v: T) -> Self
where
T: Any + 'static,
{
Self {
key: k,
value: Box::new(v),
data_type: TypeId::of::<T>(),
}
}
fn update<T>(&mut self, new_value: T)
where
T: Any + 'static,
{
self.data_type = TypeId::of::<T>();
self.value = Box::new(new_value);
}
fn get<T>(&'a self) -> &'a T
where
T: Any + 'static,
{
self.value.downcast_ref::<T>().unwrap()
}
fn get_mut<T>(&'a mut self) -> &'a mut T
where
T: Any + 'static,
{
self.value.downcast_mut::<T>().unwrap()
}
}
#[derive(Debug)]
struct Database<'a> {
data: HashMap<&'a str, Pair<'a>>,
}
impl<'a> Database<'a> {
fn new() -> Self {
Self {
data: HashMap::new(),
}
}
fn insert(&mut self, data: Pair<'a>) {
self.data.insert(data.key, data);
}
fn find(&self, key: &str) -> &'a Pair {
self.data.get(key).unwrap()
}
fn find_mut(&mut self, key: &str) -> &'a mut Pair {
self.data.get_mut(key).unwrap()
}
fn remove(&mut self, key: &str) {
self.data.remove(key);
}
}
#[derive(Debug)]
struct Position {
x: f32,
y: f32,
}
fn main() {
let mut db = Database::new();
// add data
{
let pair1 = Pair::new("testkey", "Awesome string...".to_owned());
let pair2 = Pair::new("position", Position { x: 0.0, y: 0.0 });
db.insert(pair1);
db.insert(pair2);
}
// change data
{
let pair = db.find_mut("position");
pair.get_mut::<Position>().x = 50.0;
} // <--- end of &mut Pair
// read data
let pos = db.find("position");
println!("{:?}", pos);
}
error[E0502]: cannot borrow `db` as immutable because it is also borrowed as mutable
--> src/main.rs:101:15
|
96 | let pair = db.find_mut("position");
| -- mutable borrow occurs here
...
101 | let pos = db.find("position");
| ^^
| |
| immutable borrow occurs here
| mutable borrow later used here
我不明白这里的借阅检查器。我把所有东西都放在了pair
不存在的db.find("position")
。为什么不起作用?如果我正确理解文档,那就是在嵌套范围内使用可变变量。
我写了一个更简单的例子,我来自:
fn main() {
let mut x = 5;
{
let y = &mut x;
*y = 10;
}
println!("{}", x);
}
这按预期工作。我真的被借阅检查员困住了。
TL; DR
fn get<T>(&self) -> &T
fn get_mut<T>(&mut self) -> &mut T
fn find(&self) -> &Pair<'a>
fn find_mut(&mut self) -> &mut Pair<'a>
创建一个MCVE是一个非常重要的技能,成为一个有效的程序员。我们在the tag wiki上编写特定于Rust的技术。这是您的代码之一:
#[derive(Debug, Default)]
struct Pair<'a>(&'a str);
#[derive(Debug, Default)]
struct Database<'a> {
data: &'a str,
}
impl<'a> Database<'a> {
fn find(&self) -> &'a Pair {
unimplemented!()
}
fn find_mut(&mut self) -> &'a mut Pair {
unimplemented!()
}
}
fn main() {
let mut db = Database::default();
{
db.find_mut();
}
db.find();
}
之所以出现这个问题,是因为如果没有正确的话,你就会把生命周期都撒上来特别:
fn find(&self) -> &'a Pair
fn find_mut(&mut self) -> &'a mut Pair
这些方法表示他们将返回对Pair
的引用,该引用的持续时间与插入Database
的数据一样长。这不可能是因为您插入的数据是&'static str
。
你真的想要:
fn find(&self) -> &Pair<'a>
fn find_mut(&mut self) -> &mut Pair<'a>
将#![deny(rust_2018_idioms)]
添加到您的箱子有助于捕获这些,虽然错误消息还不完美:
error: hidden lifetime parameters in types are deprecated
--> src/main.rs:12:27
|
12 | fn find(&self) -> &'a Pair {
| ^^^^- help: indicate the anonymous lifetime: `<'_>`
error: hidden lifetime parameters in types are deprecated
--> src/main.rs:16:39
|
16 | fn find_mut(&mut self) -> &'a mut Pair {
| ^^^^- help: indicate the anonymous lifetime: `<'_>`
如果我们再扩展到完整的原始问题,我们会发现问题仍然没有消失。既然我们在Pair
的生命周期中遇到了问题,那么让我们看看是否还有其他相关问题:
fn get<T>(&'a self) -> &'a T
fn get_mut<T>(&'a mut self) -> &'a mut T
这表明self
将和self.key
一样长,这不是你想要的99%的时间。删除这些explcit生命周期,以允许正常的生命周期省略:
fn get<T>(&self) -> &T
fn get_mut<T>(&mut self) -> &mut T
也可以看看: