如何解决此代码中的生命周期问题?

时间:2017-12-10 10:16:26

标签: rust lifetime

pub struct Map<'a, F, I, O>
    where F: Fn(I) -> O {
    parser: &'a Parser<'a>,
    mapper: F,
    phantomDataI: PhantomData<I>,
    phantomDataO: PhantomData<O>
}

impl<'a, F, I, O> Map<'a, F, I, O> 
    where F: Fn(I) -> O {
    fn new(parser: &'a Parser, mapper: F) -> Map<'a, F, I, O> {
        Map { parser, mapper, phantomDataI: PhantomData, phantomDataO: PhantomData }
    }        
}

当我编译它时,我得到一个错误......

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
    --> src\combinator\mod.rs:123:9
    |
123 |         Map { parser, mapper, phantomDataI: PhantomData, phantomDataO: PhantomData }
    |         ^^^
    |
note: first, the lifetime cannot outlive the lifetime 'a as defined on the impl at 120:1...
--> src\combinator\mod.rs:120:1
    |
120 | / impl<'a, F, I, O> Map<'a, F, I, O>
121 | |     where F: Fn(I) -> O {
122 | |     fn new(parser: &'a Parser, mapper: F) -> Map<'a, F, I, O> {
123 | |         Map { parser, mapper, phantomDataI: PhantomData, phantomDataO: PhantomData }
124 | |     }
125 | | }
    | |_^
note: ...so that expression is assignable (expected combinator::Map<'a, _, _, _>, found combinator::Map<'_, _, _, _>)
--> src\combinator\mod.rs:123:9
    |
123 |         Map { parser, mapper, phantomDataI: PhantomData, phantomDataO: PhantomData }
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: but, the lifetime must be valid for the anonymous lifetime #1 defined on the method body at 122:5...
--> src\combinator\mod.rs:122:5
    |
122 | /     fn new(parser: &'a Parser, mapper: F) -> Map<'a, F, I, O> {
123 | |         Map { parser, mapper, phantomDataI: PhantomData, phantomDataO: PhantomData }
124 | |     }
    | |_____^
note: ...so that types are compatible (expected combinator::Parser<'_>, found combinator::Parser<'_>)
--> src\combinator\mod.rs:123:15
    |
123 |         Map { parser, mapper, phantomDataI: PhantomData, phantomDataO: PhantomData }
    |               ^^^^^^

我不明白为什么会出现这条线

表达式是可分配的(预期组合符:: Map&lt;'a,_,_,&gt;,找到组合符:: Map&lt;',_,_,_&gt;)

我是否需要以某种方式更改我的终身说明符?

1 个答案:

答案 0 :(得分:1)

Parser签名中的

new需要'a生命周期参数:

fn new(parser: &'a Parser<'a>, mapper: F) -> Map<'a, F, I, O>