该Path
参数可以立即转换为 a PathBuf
,但这似乎效率低下。必须有某种方法来保留 a Path
,对吗?
use std::{fs::File, path::Path};
struct Foo {
a: Option<File>,
b: Option<File>,
}
struct FooBuilder<'a> {
a: Option<&'a Path>,
b: Option<&'a Path>,
}
impl<'a> FooBuilder<'a> {
fn new() -> FooBuilder<'a> {
FooBuilder { a: None, b: None }
}
fn a<P: AsRef<Path> + 'a>(&'a mut self, a: P) -> &mut FooBuilder<'a> {
self.a = Some(a.as_ref());
self
}
fn b<P: AsRef<Path> + 'a>(&'a mut self, b: P) -> &mut FooBuilder<'a> {
self.b = Some(b.as_ref());
self
}
fn done(&self) -> Foo {
Foo {
a: match self.a {
Some(path) => Some(File::open(path).unwrap()),
None => None,
},
b: match self.b {
Some(path) => Some(File::open(path).unwrap()),
None => None,
},
}
}
}
fn main() {
let path1 = Path::new("1");
let path2 = Path::new("2");
let _foo = FooBuilder::new().a(path1).b(path2).done();
}
error[E0597]: `a` does not live long enough
--> src/main.rs:19:23
|
13 | impl<'a> FooBuilder<'a> {
| -- lifetime `'a` defined here
...
19 | self.a = Some(a.as_ref());
| --------------^----------
| | |
| | borrowed value does not live long enough
| assignment requires that `a` is borrowed for `'a`
20 | self
21 | }
| - `a` dropped here while still borrowed
error[E0597]: `b` does not live long enough
--> src/main.rs:24:23
|
13 | impl<'a> FooBuilder<'a> {
| -- lifetime `'a` defined here
...
24 | self.b = Some(b.as_ref());
| --------------^----------
| | |
| | borrowed value does not live long enough
| assignment requires that `b` is borrowed for `'a`
25 | self
26 | }
| - `b` dropped here while still borrowed