What is the best practice for instantiating a structure?

I am trying to figure out what is best for instantiating struct. In C ++, I would pass everything that I need to the constructor and throw an exception if structit could not be created. In rust, I was told to create a method that returns Result. But doesn't that work too much? Why not easy fail!()?

Also, if returning Resultis the way to go, does that mean that all structures will need a factory?

+4
source share
1 answer

The base constructor for YourStructshould be a static method called YourStruct::new()(for more details, see Rust Style Guides ).

For the return type, use YourStructif nothing goes wrong, or if you use fail!(). Use Option<YourStruct>if there is only one obvious reason for the failure of the constructor. Use Result<YourStruct, YourStructErr>if it would be useful for the caller to find out why he failed. The problem with this fail!()is that it prevents the caller from retrying or sending a message with a good message to the user, or anything else that the caller can do. In certain situations, it fail!()may be in order.

+6
source

All Articles