How to return temporary value and make it live longer

#1

Hi,
I want to create new object and then use a function over it, that return reference to it like this:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=26e5b59218dca3c64c3626627ab020b7
Any solutions?

#2

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.

1 Like
#3

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>.

https://doc.rust-lang.org/1.0.0/style/ownership/builders.html

2 Likes
#4

Okay I make it like this example and it seems to work, but is it good practise?

#5

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 arg and args functions. Usually I go with either:

  1. A structure with a member that is a configuration structure
  2. A few modifiers in the struct that are defined like fn add_something(&mut self, s: Something)
1 Like
#6

Alright. Thanks!