为什么一个非消耗性构建器编译而另一个不编译?

Why does one non-consuming builder compile while another does not?

我阅读了 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

您的生命周期存在问题:您正在为太多不同的事物重复使用相同的生命周期 ('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
    }
}