对于以下Rust代码:
fn facing_of_mut<'a>(domain: &'a mut Domain, entity: Entity) -> Option<&'a mut Direction> {
component_of_mut(&mut domain, entity)
}
......编译器输出:
error: `domain` does not live long enough
--> src/facing.rs:5:27
|
5 | component_of_mut(&mut domain, entity)
| ^^^^^^ does not live long enough
6 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the body at 4:90...
--> src/facing.rs:4:91
|
4 | fn facing_of_mut<'a>(domain: &'a mut Domain, entity: Entity) -> Option<&'a mut Direction> {
| ___________________________________________________________________________________________^ starting here...
5 | | component_of_mut(&mut domain, entity)
6 | | }
| |_^ ...ending here
我不理解错误消息,因为我认为声明这些生命周期的目的特别要求,只要domain
参考Direction
参数存在,就会传递任何对象。在返回值中,该值取决于domain
分配的内存。
component_of_mut
的签名是:
pub fn component_of_mut<'a, C: 'static>(domain: &'a mut Domain, entity: Entity) -> Option<&'a mut C>
...我可以在单元测试中直接调用它,而不会在编译期间出现生命周期错误。只有在facing_of_mut
调用它时我才会收到错误。
答案 0 :(得分:4)
您正在参考domain
。 domain
是参数的局部变量,并且已经是引用。 domain
仅持续函数调用的持续时间,因此可以存在对该值的引用的长度。
要修复它,请不要尝试引用参考:
type Domain = String;
type Entity = String;
type Direction = String;
pub fn component_of_mut<'a, C>(domain: &'a mut Domain, entity: Entity) -> Option<&'a mut C>
where C: 'static
{
unimplemented!()
}
fn facing_of_mut<'a>(domain: &'a mut Domain, entity: Entity) -> Option<&'a mut Direction> {
component_of_mut(domain, entity)
}
fn main() {}