Parsing integers from strings is a fundamental skill in Rust programming. Whether you're reading configuration files, processing user input, or parsing network protocols, you'll frequently need to convert text into numeric values.
Rust provides several methods for parsing integers. The most common is the .parse() method, which uses the FromStr trait to convert strings into typed values. For parsing numbers in different bases (binary, octal, hexadecimal), Rust provides the from_str_radix() function on integer types.
Understanding how to handle parsing errors is equally important. When parsing fails, Rust returns a ParseIntError that you can handle gracefully using Result combinators like ok(), map_err(), or pattern matching.
Implement the following functions that demonstrate various integer parsing techniques:
parse_decimal - Parse a string as a decimal (base 10) i32
Some(value) on success, None on failureparse_binary - Parse a binary string (e.g., "1010") as a u32
Some(value) on success, None on failureparse_hex - Parse a hexadecimal string (e.g., "FF" or "ff") as a u32
Some(value) on success, None on failureparse_octal - Parse an octal string (e.g., "77") as a u32
Some(value) on success, None on failureparse_with_radix - Parse a string with any radix from 2 to 36
Some(value) on success, None on failureparse_multiple - Parse a comma-separated string of integers
Vec<i32> containing all successfully parsed numberstry_parse_u8 - Parse a string as a u8 (0-255)
Ok(value) on successErr(String) with a descriptive error message on failuredetect_and_parse - Automatically detect the base and parse
Some(i64) on success, None on failureuse integer_parsing::*;
// Basic decimal parsing
assert_eq!(parse_decimal("42"), Some(42));
assert_eq!(parse_decimal("-17"), Some(-17));
assert_eq!(parse_decimal("not_a_number"), None);
// Binary parsing
assert_eq!(parse_binary("1010"), Some(10));
assert_eq!(parse_binary("11111111"), Some(255));
// Hexadecimal parsing
assert_eq!(parse_hex("FF"), Some(255));
assert_eq!(parse_hex("ff"), Some(255));
assert_eq!(parse_hex("1a2b"), Some(6699));
// Octal parsing
assert_eq!(parse_octal("77"), Some(63));
assert_eq!(parse_octal("10"), Some(8));
// Custom radix parsing
assert_eq!(parse_with_radix("Z", 36), Some(35));
assert_eq!(parse_with_radix("10", 2), Some(2));
// Multiple values
assert_eq!(parse_multiple("1, 2, 3"), vec![1, 2, 3]);
assert_eq!(parse_multiple("1, bad, 3"), vec![1, 3]);
// Safe u8 parsing with error messages
assert_eq!(try_parse_u8("100"), Ok(100));
assert!(try_parse_u8("256").is_err()); // Overflow
// Auto-detect base
assert_eq!(detect_and_parse("0xFF"), Some(255));
assert_eq!(detect_and_parse("0b1010"), Some(10));
assert_eq!(detect_and_parse("0o77"), Some(63));
assert_eq!(detect_and_parse("42"), Some(42));.parse::<Type>() for standard decimal parsingType::from_str_radix(s, radix) for parsing with specific basesok() method converts Result<T, E> to Option<T>parse_multiple, use .split(',') and .filter_map() to handle failuresfrom_str_radix returns a Result, so you need to handle the error casedetect_and_parse, use strip_prefix() to remove and check prefixes.trim()