当直接调用函数时,可变引用的寿命足够长,但在通过中间函数调用时,它的寿命不够长

时间:2017-02-13 02:39:58

标签: rust lifetime-scoping

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

1 个答案:

答案 0 :(得分:4)

您正在参考domaindomain是参数的局部变量,并且已经是引用。 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() {}