查看 std::cell::Cell 的文档,我没有找到如何检索内部数据的不可变引用。只有 get_mut
方法:https://doc.rust-lang.org/std/cell/struct.Cell.html#method.get_mut
我不想使用此函数,因为我想要 &self
而不是 &self mut
。
我发现另一个解决方案是获取原始指针:
use std::cell::Cell;
struct DbObject {
key: Cell<String>,
data: String
}
impl DbObject {
pub fn new(data: String) -> Self {
Self {
key: Cell::new("some_uuid".into()),
data,
}
}
pub fn assert_key(&self) -> &str {
// setup key in the future if is empty...
let key = self.key.as_ptr();
unsafe {
let inner = key.as_ref().unwrap();
return inner;
}
}
}
fn main() {
let obj = DbObject::new("some data...".into());
let key = obj.assert_key();
println!("Key: {}", key);
}
有没有不使用 unsafe 的方法来做到这一点?如果没有,也许在这里使用 RefCell 会更实际一些?
谢谢你的帮助!