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? (new_labeled_graph attempts to reuse new)



You have to make the variable g mutable like this:

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


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



@ogen @flavius

This syntax may also be helpful for you:

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

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