使用构建器模式的所有权错误

Ownership error using builder pattern

我试图在 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

因为您没有将生成器存储在任何地方。如果它没有存储在任何地方,它最多只存在于该表达式的持续时间内。所以在表达式的末尾,你有一个 &mut MediaType 指向一个即将被销毁的值。

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