1
我读the builder pattern,然后试图建立2个不同的制造商(Header
和Request
)如下:为什么一个非耗时的编译器会编译,而另一个却不会?
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
事实上,你也可以摆脱第二次的生命'的价值! –
@ DanielWorthington-Bodart:的确,我错过了它。 –