Reuse a constructor in another constructor

For a struct, I have two constructors, a "naked" one and one which sets more fields.

What I need is to reuse one of the constructors in the other constructor, BUT without giving up the principle "an object must be consistent at all times".

Thus I would like to avoid setters, since it introduces the risk of being made public (even though it wouldn't be at the beginning).

The problem is that I need a mutable reference to self &mut self, because I need to mutate a field of the structure, but neither of the constructors have a self, since self is about to get constructed in the first place.

So how would I solve this problem in an idiomatic way?

Rust Playground (new_labeled_graph attempts to reuse new)

Thanks

You have to make the variable g mutable like this:

fn new_labeled_graph(data: &str) -> Graph {
    let mut g = Graph::new();
    g.data = data.to_string();
    g
}
1 Like

Oh that should have been so obvious, I almost feel ashamed.

Thanks!

@ogen @flavius

This syntax may also be helpful for you:

fn new_labeled_graph(data: &str) -> Graph {
    Graph {
        data: data.to_string(),
        ..Graph::new()
    }
}

That will set data to data.to_string(), and take the rest of the values from Graph::new().

1 Like