2

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

4

1 回答 1

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() {}
于 2017-02-13T02:48:07.627 回答