Several return types from a method

I am trying to write a simple alias for a TV episode file in Rust.

The file identifier is parsed and can be one of several types (based on date, season / episode number, etc.). Then this analyzed file turns into a “populated file” with data from the database (which is then formatted with a new file name).

First I tried the method to parsetake the file name and return an enumeration option:

enum ParsedFile{
    DateBased{series: String, date: Date},
    SeasonBased{series: String, season: i32, episode: i32},
    // etc
}


fn parse(fname:&str) -> Option<ParsedFile>{
    ...
}

This worked well, but the methods of taking ParsedFileand doing different things for each episode became dirty

For example, to separate the translation ParsedFile->PopulatedFileinto separate methods, I need to map the options, and then destroy them in the method

struct PopulatedFile {
    seriesname: String,
    season: i32,
    episode: i32,
    episodename: String,
    airdate: Date,
}

fn _populate_seasonbased(file: ParsedFile) -> Result<PopulatedFile, TvdbError>{
    // can't just access file.season or file.episode, have to destructure enum again
}

fn populate(f: ParsedFile) -> Result<PopulatedFile, TvdbError> {
    return match f {
        ParsedFile::DateBased{..} => 
            _populate_datebased(f),
        // ...
    }
}

, , .

, :

struct DateBased{
    series: String,
    date: Date
}
struct SeasonBased{
    series: String,
    season: i32,
    episode: i32
}

.. , , ToPopulatedFile . parse (, , DateBased struct SeasonBased)

?

+4
1

trait, , , , :

struct DateBased{
    series: String,
    date: Date
}

struct SeasonBased{
    series: String,
    season: i32,
    episode: i32
}

enum ParsedFile{
    Date(DateBased),
    Season(SeasonBased),
    // etc
}

fn _populate_datebased(file: DateBased) -> Result<PopulatedFile, TvdbError>;

fn _populate_seasonbased(file: SeasonBased) -> Result<PopulatedFile, TvdbError>;

fn populate(f: ParsedFile) -> Result<PopulatedFile, TvdbError> {
    return match f {
        ParsedFile::Date(d) => _populate_datebased(d),
        // ...
    }
}

enum struct Rust, , , , .

+4

All Articles