Skip to content

Instantly share code, notes, and snippets.

@Aloxaf
Created Oct 13, 2018
Embed
What would you like to do?
Rust read function for OJ
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