再次生锈

时间:2015-06-30 11:32:08

标签: rust lifetime

所以在这里我编写了用于生成排列的迭代器:

pub struct Permutations {
    size: usize,
    arr: Vec<usize>,
}

impl Permutations {
    pub fn new(size: usize) -> Permutations {
        Permutations{
            size: size,
            arr: (0..size).collect::<Vec<_>>(),
        }
    }
}

impl Iterator for Permutations {
    type Item = Vec<usize>;

    fn next(&mut self) -> Option<Self::Item> {
        // some complex code here
        if ok { Some(self.arr.clone()) } else { None }
    }
}

现在,我想要的是每次都不克隆向量,并返回一个常量引用。所以我写道:

impl Iterator for Permutations {
    type Item = &Vec<usize>;

    fn next(&mut self) -> Option<Self::Item> {
        // some complex code here
        if ok { Some(self.arr.clone()) } else { None }
    }
}

当然这不会编译,因为我需要指定生命周期。好的,我们试一试:

impl<'a> Iterator for Permutations {
    type Item = &'a Vec<usize>;

    fn next(&mut self) -> Option<Self::Item> {
        // some complex code here
        if ok { Some(&self.arr) } else { None }
    }
}

现在我收到一个错误:

error: the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates

所以,我不知道,这意味着什么,但是好吧,我想我们需要以某种方式将这一切都束缚在自我身上。经过一番探索并与难以理解的错误作斗争后,出现了:

use std::marker::PhantomData;

pub struct Permutations<'a> {
    size: usize,
    arr: Vec<usize>,
    p: PhantomData<&'a Vec<usize>>,
}

impl<'a> Permutations<'a> {
    pub fn new(size: usize) -> Permutations<'a> {
        Permutations{
            size: size,
            arr: (0..size).collect::<Vec<_>>(),
            p: PhantomData,
        }
    }
}

impl<'a> Iterator for Permutations<'a> {
    type Item = &'a Vec<usize>;

    fn next(&mut self) -> Option<Self::Item> {
        // some complex code here
        if ok { Some(&self.arr) } else { None }
    }
}

但是又有一个错误,虽然有点可以理解:

error: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
    return Some(&self.arr);
help: consider using an explicit lifetime parameter as shown: fn next(&'a mut self) -> Option<Self::Item>

好!这实际上非常有用!让我们添加显式生命周期:

impl<'a> Iterator for Permutations<'a> {
    type Item = &'a Vec<usize>;

    fn next(&'a mut self) -> Option<Self::Item> {
        // some complex code here
        if ok { Some(&self.arr) } else { None }
    }
}

的Bam!就像我想的那样:根本没用。

error: method `next` has an incompatible type for trait: expected bound lifetime parameter , found concrete lifetime

Sooo ...是的。我如何在世界上做这个最简单的事情?

0 个答案:

没有答案