I'm trying to understand what's the best practice for creating instances of a struct
. In C++ I'd pass everything I need to the constructor and throw an exception if the struct
could not be created. In rust I've been told to create a method that returns a Result
. But isn't this too much work? Why not just fail!()
?
Also, if returning Result
is the way to go, does this mean that all structs will need a factory?
A basic constructor for YourStruct
should be a static method called YourStruct::new()
(see the Rust style guidelines for more info).
For the return type, use YourStruct
if nothing can go wrong or if you use fail!()
. Use Option<YourStruct>
if there's only one obvious reason for the constructor failing. Use Result<YourStruct, YourStructErr>
if it would be helpful to the caller to know why it failed. The problem with fail!()
is it doesn't give the caller a chance to try again, or pass a nice error message back to the user, or whatever else the caller might want to do. In certain situations, fail!()
might be okay.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With