使用构建器模式

时间:2015-08-21 11:10:17

标签: rust ownership borrow-checker

我尝试在Builder pattern之后编写一个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())));

做好工作。为什么借用检查器会抱怨虽然在直接使用该值时没有抱怨,但我遵循了构建器模式示例?

Rust Playground

1 个答案:

答案 0 :(得分:2)

因为您不会将构建器存储在任何位置。如果它没有存储在任何地方,它最多只存在于该表达式的持续时间。因此,在表达式的末尾,您有一个&mut MediaType指向即将被销毁的值。

如果查看链接文档中的示例,作者要么在单个表达式中完全使用构建器,要么存储::new()调用的结果。你不能借一个临时的,然后借用的商店。