我想编写一个可以存储任何内容的简单键/值存储。我从一个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")
。为什么不起作用?如果我对文档的理解正确,那就是在嵌套范围内使用可变的var。
我写了一个简单的例子,我来自:
fn main() {
let mut x = 5;
{
let y = &mut x;
*y = 10;
}
println!("{}", x);
}
这按预期工作。我真的迷上了借阅检查器。
答案 0 :(得分:2)
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%的时间所希望的。删除这些显式寿命,以允许正常的寿命消除:
fn get<T>(&self) -> &T
fn get_mut<T>(&mut self) -> &mut T
另请参阅: