我尝试按照Builder 模式编写 API,该示例已大大简化,但编译器仍然抱怨借用值的寿命不够长。
#[derive(Debug)]
pub struct MediaType {
toptype: Option<String>,
subtype: Option<String>,
}
impl MediaType {
pub fn new() -> MediaType {
MediaType {
toptype: None,
subtype: None,
}
}
pub fn toptype<'a>(&'a mut self, toptype: Option<String>) -> &'a mut MediaType {
self.toptype = toptype;
self
}
pub fn subtype<'a>(&'a mut self, subtype: Option<String>) -> &'a mut MediaType {
self.subtype = subtype;
self
}
}
fn main() {
let mut tag = MediaType::new().toptype(Some("text".to_owned())).subtype(Some("html".to_owned()));
println!("{:?}", tag);
}
产生的错误信息是:
<anon>:27:20: 27:36 error: borrowed value does not live long enough
<anon>:27 let mut tag = MediaType::new().toptype(Some("text".to_owned())).subtype(Some("html".to_owned()));
^~~~~~~~~~~~~~~~
<anon>:27:103: 29:2 note: reference must be valid for the block suffix following statement 0 at 27:102...
<anon>:27 let mut tag = MediaType::new().toptype(Some("text".to_owned())).subtype(Some("html".to_owned()));
<anon>:28 println!("{:?}", tag);
<anon>:29 }
<anon>:27:5: 27:103 note: ...but borrowed value is only valid for the statement at 27:4
<anon>:27 let mut tag = MediaType::new().toptype(Some("text".to_owned())).subtype(Some("html".to_owned()));
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:27:5: 27:103 help: consider using a `let` binding to increase its lifetime
<anon>:27 let mut tag = MediaType::new().toptype(Some("text".to_owned())).subtype(Some("html".to_owned()));
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
playpen: application terminated with error code 101
都使用两个班轮
let mut tag = MediaType::new();
tag.toptype(Some("text".to_owned())).subtype(Some("html".to_owned()));
并直接打印 MediaType
println!("{:?}", MediaType::new().toptype(Some("text".to_owned())).subtype(Some("html".to_owned())));
做工作。为什么借用检查器会抱怨,尽管在直接使用该值并且我遵循构建器模式示例时它没有抱怨?