3

我尝试按照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())));

做工作。为什么借用检查器会抱怨,尽管在直接使用该值并且我遵循构建器模式示例时它没有抱怨?

锈游乐场

4

1 回答 1

2

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

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

于 2015-08-21T11:29:17.977 回答