Integer Operations with ard/int
The ard/int module provides functions for converting and parsing integers.
The int module provides:
- String parsing to convert strings to integers
- Error handling with Maybe types for failed conversions
use ard/int
fn main() { let num = Int::from_str("42").or(0)}fn from_str(str: Str) Int?
Section titled “fn from_str(str: Str) Int?”Parse a string into an integer. Returns a Maybe type - some if parsing succeeds, none if it fails.
use ard/int
let num = Int::from_str("42")match num { val => io::print(val.to_str()), _ => io::print("Failed to parse")}Examples
Section titled “Examples”Parse Integer from User Input
Section titled “Parse Integer from User Input”use ard/intuse ard/io
fn main() { io::print("Enter a number: ") let input = io::read_line().expect("Failed to read")
match Int::from_str(input) { val => io::print("You entered: {val.to_str()}"), _ => io::print("Invalid integer") }}Use with Default Value
Section titled “Use with Default Value”use ard/int
fn main() { let age = Int::from_str("thirty").or(18) // age is 18 since parsing failed}Validate User Input
Section titled “Validate User Input”use ard/intuse ard/io
fn main() { io::print("Enter age (1-120): ") let input = io::read_line().expect("Failed to read")
match Int::from_str(input) { age => { if age >= 1 and age <= 120 { io::print("Valid age: {age.to_str()}") } else { io::print("Age out of valid range") } }, _ => io::print("Invalid integer") }}