-
-
Save lluchs/41fdbc8deb13473a535c1ce06d0acd93 to your computer and use it in GitHub Desktop.
Rust builder pattern with lifetime on struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Foo; | |
struct FooBuilder<'a> { | |
foo: &'a Foo, | |
} | |
impl Foo { | |
fn build(&self) -> FooBuilder { | |
FooBuilder { foo: &self } | |
} | |
} | |
impl<'a> FooBuilder<'a> { | |
// correct: other lifetime for self | |
fn enable<'b>(&'b mut self) -> &'b mut FooBuilder<'a> { | |
self | |
} | |
// wrong: can only call once | |
fn disable(&'a mut self) -> &'a mut FooBuilder { | |
self | |
} | |
} | |
fn main() { | |
let foo = Foo {}; | |
let mut builder = foo.build(); | |
builder.enable(); | |
builder.disable(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment