November 2017
Intermediate to advanced
264 pages
5h 45m
English
Another way to obtain the same result is to wrap the dangerous read operation in a separate function, here the function read_u32() returns an Option type value to be tested in the main code:
// see code in Chapter 5/code/input_number2.rs
use std::io; fn main() { println!("Give an integer number bigger than 0:"); let num = read_u32(); match num { Some(val) => println!("That's the number: {}", val), None => println!("Failed to read number.") } } fn read_u32() -> Option<u32> { let mut buf = String::new(); if io::stdin().read_line(&mut buf).is_ok() { let result = buf.trim().parse::<u32>(); return match result { // (1) Ok(value) => Some(value), Err(_) => None //Failed to parse }; } None //Failed to read from ...Read now
Unlock full access