2017-10-08 18 views
1

我試圖實現Index特質的結構與生命時間和鬥爭。我想要一個內部向量可在&str上索引。即myqstr["foo"]具有&str和生命期的索引特質

這裏是我的了:

pub struct QString<'a> { 
    pub params: Vec<Param<'a>> 
} 

pub struct Param<'a> { 
    pub name: &'a str, 
    pub value: &'a str, 
} 

impl<'a, 'b> ::std::ops::Index<&'b str> for QString<'a> { 
    type Output = Param<'a>; 
    fn index(&self, index: &'b str) -> &Param<'a> { 
     &self.params.iter() 
      .rposition(|ref p| p.name == index) 
      .map(|pos| self.params[pos]) 
      .unwrap() 
    } 
} 

和錯誤是經典。

Compiling qstring v0.1.0 (file:///Users/martin/dev/qstring) 
error[E0597]: borrowed value does not live long enough 
    --> src/lib.rs:113:10 
    | 
113 |   &self.params.iter() 
    | __________^ 
114 | |    .rposition(|ref p| p.name == index) 
115 | |    .map(|pos| self.params[pos]) 
116 | |    .unwrap() 
    | |_____________________^ does not live long enough 
117 |  } 
    |  - temporary value only lives until here 
    | 
note: borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 112:5 

我明白Index要我返回索引結構借用價值,我知道我要回什麼是'a壽命,但是,甚至有可能在這種情況下?

回答

3

你在錯誤的地方參考,你想參考你的.map函數。

self.params.iter() 
    .rposition(|ref p| p.name == index) 
    .map(|pos| &self.params[pos]) 
    .unwrap() 

因爲您想引用Vec本身中的參數。

這也將會是容易做

self.params.iter() 
    .rev() 
    .find(|p| p.name == index) 
    .unwrap() 
+0

的感謝!是rev()零成本?我的意思是如果我想效率? –

+0

是的,'.rev()'只存在於可以從任一端顯式迭代的類型中,因此效率很高。 – loganfsmyth

+0

@MartinAlgesten,是的,這是零成本。如果我想改變''輸出=選項>''以擺脫那個'unwrap()','rev()'僅適用於'DoubleEndedIterator' – red75prime