Question about constructors

I have been following the book and in the code examples it is very common that whenever a struct is defined, a constructor is implemented like this:

struct TestStruct {
    a: u32,
}

impl TestStruct {
    fn new(a: u32) -> Self {
        TestStruct {
            a
        }
    }
}

Why is this new() function defined? Is there a difference between creating new instances of TestStruct using

let struct_1 = TestStruct::new(5);

and

let struct_2 = TestStruct{
    a: 5
};

Is it just a matter of convention?

Furthermore, why I'm allow to call the new() function even though it's not declared public? Is it because it's a "class method", i.e. called on the struct rather than on the instance?

new takes positional arguments, and can be passed as a callback. TestStruct takes a named argument, so it cannot.

new can also have implementation details that are hidden from the caller, so the implementation can be changed independently of the caller, whereas TestStruct constructs the struct exactly the way it's written. You could even change the number of fields in the struct, but still have new take precisely one argument.

It's not private to the struct, but private to the module where the struct is declared.

3 Likes

Also, in practice it's more common to have a public constructor.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.