w3resource

Rust Function: Date string parsing

Rust Result and Option types: Exercise-5 with Solution

Write a Rust function that parses a date string in the format "YYYY-MM-DD" and returns Result<(i32, u32, u32), &str> indicating the year, month, and day, or an error message.

Sample Solution:

Rust Code:

fn parse_date(date_str: &str) -> Result<(i32, u32, u32), &str> {
    // Split the input string by '-' delimiter
    let parts: Vec<&str> = date_str.split('-').collect();

    // Check if the split resulted in three parts (year, month, day)
    if parts.len() != 3 {
        // If not, return an error message
        return Err("Invalid date format. Date must be in the format 'YYYY-MM-DD'");
    }

    // Parse the parts into integers (year, month, day)
    let year_result = parts[0].parse::<i32>();
    let month_result = parts[1].parse::<u32>();
    let day_result = parts[2].parse::<u32>();

    // Check if all parsing operations were successful
    if year_result.is_err() || month_result.is_err() || day_result.is_err() {
        // If any parsing failed, return an error message
        return Err("Invalid date format. Year, month, and day must be numeric.");
    }

    // Extract the parsed values
    let year = year_result.unwrap();
    let month = month_result.unwrap();
    let day = day_result.unwrap();

    // Validate the parsed values (year, month, day)
    if month < 1 || month > 12 || day < 1 || day > 31 {
        // If any value is out of range, return an error message
        return Err("Invalid date. Month must be between 1 and 12, and day must be between 1 and 31.");
    }

    // Return the parsed and validated date as a tuple
    Ok((year, month, day))
}

fn main() {
    // Test the parse_date function
    let date_str = "2018-02-10";
    match parse_date(date_str) {
        Ok((year, month, day)) => {
            println!("Parsed date: Year={}, Month={}, Day={}", year, month, day);
        }
        Err(error_msg) => {
            println!("Error: {}", error_msg);
        }
    }
}

Output:

Parsed date: Year=2018, Month=2, Day=10

Explanation:

Here's a brief explanation of the above Rust code:

This function "parse_date()" takes a string 'date_str' as input, attempts to parse it into year, month, and day components, and returns a 'Result' indicating either the parsed date or an error message if parsing fails. The function splits the input string by the '-' delimiter, parses each part into integers, and then validates the parsed values to ensure they represent a valid date. Finally, it returns the parsed date as a tuple (i32, u32, u32) if successful, or an error message if parsing fails or the date is invalid.

Rust Code Editor:

Previous: Rust Function: Square root calculation.
Next: Rust Function: String length.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.