Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best practice for creating instances of a struct?

Tags:

struct

rust

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?

like image 397
ruipacheco Avatar asked Aug 12 '14 21:08

ruipacheco


1 Answers

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.

like image 141
Paige Ruten Avatar answered Oct 20 '22 21:10

Paige Ruten