Menu
CoddyTech

Parsing and Validation

Lesson 27 of 48 in Coddy's Rust for C# Developers course.

C# int.TryParse reports success with a boolean and writes through an out parameter. Rust's parse::<i32>() returns Result<i32, ParseIntError>, keeping the parsed value and failure state in one typed result. Neither API alone validates the application's complete domain. The examples trim one standalone integer token and then parse it, rather than splitting structured input. C# specifies invariant culture and a restricted number style so a leading sign is accepted without culture-dependent formatting. Rust integer parsing does not silently trim surrounding whitespace; the explicit trim is significant. An empty token, malformed digit sequence, or out-of-range integer fails. Converting a Result with ok() deliberately discards its error information and yields an Option, which is useful only when the caller no longer needs the reason. Retain typed errors when the user needs a distinction between parsing failure and later domain rejection.

Complete C# program:

using System;
using System.Globalization;
class Program {
    static void Main() {
        int value;
        bool ok = int.TryParse(" +24 ".Trim(), NumberStyles.AllowLeadingSign,
            CultureInfo.InvariantCulture, out value);
        Console.WriteLine(ok ? value.ToString(CultureInfo.InvariantCulture) : "invalid");
    }
}

Complete Rust program:

fn main() {
    let token = " +24 ";
    match token.trim().parse::<i32>() {
        Ok(value) => println!("{}", value),
        Err(_) => println!("invalid"),
    }
}
challenge icon

Challenge

Easy

Implement pub fn parse_pair(text: &str) -> Result<(i32, i32), String> in parser.rs. Accept exactly two colon-separated fields. Trim surrounding whitespace in each field. Each field must parse as an i32 using Rust decimal integer parsing. Validate in this order: wrong field count gives format; a parse failure in either field gives integer; only after both parse, a value outside -100 through 100 gives range. Errors are owned strings. solve passes the entire input to the API and returns ok:sum or error:reason. A leading plus or minus is accepted by integer parsing; interior whitespace, empty fields and overflow are parse failures.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, parser.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod parser;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
assert_eq!(parser::parse_pair(" -17 : +23 "), Ok((-17, 23)));
assert_eq!(parser::parse_pair("100:-100"), Ok((100, -100)));
assert_eq!(parser::parse_pair("101:bad"), Err(String::from("integer")));
assert_eq!(parser::parse_pair("101:2"), Err(String::from("range")));
assert_eq!(parser::parse_pair("1:2:3"), Err(String::from("format")));
assert_eq!(parser::parse_pair(":"), Err(String::from("integer")));
assert_eq!(parser::parse_pair(""), Err(String::from("format")));
assert_eq!(parser::parse_pair("2147483648:0"), Err(String::from("integer")));

    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for C# Developers

Practice on your own: Online Rust compiler