2016-12-28 41 views
1

我讀the builder pattern,然後試圖建立2個不同的製造商(HeaderRequest)如下:爲什麼一個非耗時的編譯器會編譯,而另一個卻不會?

use std::ascii::AsciiExt; 

#[derive(PartialEq, Debug)] 
pub struct Headers<'a> (pub Vec<(&'a str, String)>); 

impl<'a> Headers<'a> { 
    pub fn replace(&'a mut self, name: &'a str, value:&str) -> &mut Headers<'a> { 
     self.0.retain(|&(key, _)|!name.eq_ignore_ascii_case(key)); 
     self.0.push((name, value.to_string())); 
     self 
    } 
} 

#[derive(PartialEq, Debug)] 
pub struct Request<'a> { 
    pub headers: Headers<'a>, 
} 

impl<'a> Request<'a> { 
    pub fn header(&'a mut self, name: &'a str, value:&'a str) -> &mut Request<'a> { 
     self.headers.replace(name, value); 
     self 
    } 
} 

爲什麼Header編譯罰款,但Request失敗:

error[E0499]: cannot borrow `*self` as mutable more than once at a time 
    --> src/api.rs:154:9 
    | 
153 |   self.headers.replace(name, value); 
    |   ------------ first mutable borrow occurs here 
154 |   self 
    |   ^^^^ second mutable borrow occurs here 
155 |  } 
    |  - first borrow ends here 

回答

1

您有問題您的生命週期:對於太多不同的事情,您正在重複使用相同的生命週期('a),因此當編譯器嘗試使用所有這些'a的單一生命週期時得到一個令人困惑的錯誤消息。

解決方案很簡單:不要使用'a無處不在,您可以放置​​一生,但只能在必要時使用。

不需要使用&'a mut self,實例(self)不需要與它包含的&str具有相同的生命週期! (實際上不可能):

impl<'a> Headers<'a> { 
    pub fn replace(&mut self, name: &'a str, value: &str) -> &mut Headers<'a> { 
     self.0.retain(|&(key, _)|!name.eq_ignore_ascii_case(key)); 
     self.0.push((name, value.to_string())); 
     self 
    } 
} 

impl<'a> Request<'a> { 
    pub fn header(&mut self, name: &'a str, value: &str) -> &mut Request<'a> { 
     self.headers.replace(name, value); 
     self 
    } 
} 
+0

事實上,你也可以擺脫第二次的生命'的價值! –

+0

@ DanielWorthington-Bodart:的確,我錯過了它。 –

相關問題