2016-12-28 37 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:的确,我错过了它。 –

相关问题