如何创建具有对其自身类型的可选可变引用的 struct .不是自引用的,因此实例是不同的,例如
struct Environment<'a> {
outer: Option<&'a mut Environment<'a>>,
// Can be swapped for any other data
variables: HashMap<Identifier, Expression>,
}
我还try 过:
struct Environment<'a, 'b> {
outer: Option<&'a mut Environment<'b, 'b>>, //...
但没有成功.
我希望能够:
- 保留它作为引用(没有长方体),因为实例将在堆栈上
- 保持它不会对运行时性能造成额外影响(RC/RefCell)
- 在任意外部环境中改变
variables
- 不能更改
outer.outer
后面的值(因为我知道这可能会导致错误) - 保持内部环境的作用--只要外部环境存在,它就会悄悄地(排他地)borrow 外部环境(这样就不会有来自同一外部/父母的两个内部/子元素)
因此,这是一种拆分借款.其中,outer
链上的variables
个是借来的&mut
,但outer
是&
,Environment
作为一个整体也是&mut
‘d
我明白问题是&;mut T对T是不变的,有没有什么方法可以让&mut T
变成协变,就像它是&T
一样?
编辑: 所需的示例用法(未编译)
struct Environment<'a> {
outer: Option<&'a mut Environment<'a>>,
value: i32,
}
impl<'a> Environment<'a> {
fn new(value: i32) -> Self {
Self { outer: None, value }
}
fn child<'b>(&'b mut self, value: i32) -> Environment<'b>
where
// This is the relationship I would want
// parent environment outlives child environment
'a: 'b
{
Self { outer: Some(self), value }
}
}
fn user_that_creates_child(env: &mut Environment) {
let child_env = env.child(11);
// Do something with the child
child_env.outer.unwrap().value = 8; // This should be possible
// child_env.outer.unwrap().outer = // This shouldn't be
}
fn main() {
let mut root_env = Environment::new(7);
}
编译器建议与我想要的关系相反,即子函数为where 'b: 'a