Skip to content

Instantly share code, notes, and snippets.

@lluchs
Forked from anonymous/playground.rs
Last active November 14, 2020 10:57
Show Gist options
  • Save lluchs/41fdbc8deb13473a535c1ce06d0acd93 to your computer and use it in GitHub Desktop.
Save lluchs/41fdbc8deb13473a535c1ce06d0acd93 to your computer and use it in GitHub Desktop.
Rust builder pattern with lifetime on struct
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