I want to write a simple key/value store that can store anything. I started with a small wrapper around a 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
I don't understand the borrow checker here. I scoped everything so pair
don't exist by db.find("position")
. Why does it not work? If I understand the documentation correctly, it's to use mutable vars in a nested scope.
I wrote a simpler example, I came from:
fn main() {
let mut x = 5;
{
let y = &mut x;
*y = 10;
}
println!("{}", x);
}
This works as expected. I'm really stuck with the borrow checker.