I want to create new object and then use a function over it, that return reference to it like this:
The problem is that
Part1::new() on line 21 is dropped on the same line that it is created (Otherwise known as a temporary). You can fix it by creating a variable to hold the original value like in this example, but unfortunately that doesn’t work either, as you’d end up with a mutable and an immutable reference to the
Part1. In this case, I’d recommend to rethink
fn points()'s return value. Does it really need to return a reference or could it perhaps just return the new
self like in this example, but then you’d have to re-assign it every time that you wanted to modify it, so perhaps just making it take a mutable reference to
Self would be better like in this example.
One way to get around this is to follow the builder pattern - have two structs, a Part1Builder and a Part1. Part1Builder would have a points method which operates on mut self and returns Self, and has a build() method which returns a Result<Part1,Error>.
This seems to be something akin to this:
let _ = new_fn() .a() .b() .c() .d() .build();
Yes, that works but it isn’t something that I’ve seen too often in rust. Probably the most common pattern like this that I’ve seen is
std::process::Command with its
args functions. Usually I go with either:
- A structure with a member that is a configuration structure
- A few modifiers in the struct that are defined like
fn add_something(&mut self, s: Something)