对于以下 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
调用它时我才会收到错误。