Need clarity about using 'new' to create an instance

When creating a struct, one has the option to use:

 let x = X::new(...) ;

or use:

let x = X {...};

I know 'new' creates an instance of X by allocating heap(?!) memory, while doing otherwise does not; but what is the general side-effect in practical terms?
When would I want to use one instead of the other?

If I create a struct to insert as a value in a HashMap, using either seems to make no practical difference?!

In other languages, that's true. Not in Rust. new is just a convention, and it's just a function. Internally, every new will at some point use the X { ... } syntax. news can expose a default construction if they take no parameters, or they can use any parameters passed to them. Additionally, they need not be called new.

Also, you sometimes can't use X { ... } syntax, because the fields are private.

2 Likes

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.