Should I return a Result from new()?


#1

I’m creating a new() function on this enum:

enum Mode {
    OPML(PathBuf),                // Updates the blog collection from an OPML file.
    RSS(Option<Url>),             // Updates the article collection to reflect the existing RSS published links
    Crawl(Option<Url>),           // Fetches the page text of the RSS links into the article collection
    Index(Option<Collection>),    // Update index collections to reflect newly published content
    Synch(Option<Index>),         // Submit new index values to Algolia
    Unrecognized(Option<String>), // unrecognized mode
}

If URL parsing were to fail, I’d expect to return an Error and not a Mode, but I can’t see anything in the standard library where this is done. Is it acceptable to return a Result from the idiomatic constructor? And if not, how else should I structure my code?

Just to show more of how this is working I’m using string values passed at run time:

pub fn main() {
    let mode: Mode = Mode::from(env::args());

And the from will pass 2 strings to new(), the first being the Mode name and the second being the associated data.


#2

Sure - File::open is an example of this kind of constructor.


#3

I see! I don’t think std library reference docs search works how I expected. I did search for Result “In Return Types” but it doesn’t return everything, just Result<()>, which is why I didn’t see File::open. Thanks for pointing it out.