Rust read function for OJ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fmt::Debug; | |
use std::io; | |
use std::io::prelude::*; | |
use std::str::FromStr; | |
/// read into a specific type | |
/// | |
/// # Example: | |
/// | |
/// ``` | |
/// let n = read::<i32>(); | |
/// let str = read::<String>(); | |
/// ``` | |
fn read<T>() -> T | |
where | |
T: FromStr, | |
T::Err: Debug, | |
{ | |
let str = io::stdin() | |
.bytes() | |
.map(|b| b.unwrap() as char) | |
.take_while(|&c| c != ' ' && c != '\n') | |
.collect::<String>(); | |
str.trim().parse::<T>().unwrap() | |
} | |
// `cargo test -- --nocapture` | |
#[cfg(test)] | |
mod test { | |
use read; | |
#[test] | |
fn read_test() { | |
println!("i32: {}", read::<i32>()); | |
println!("f32: {}", read::<f32>()); | |
println!("str: {}", read::<String>()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment