Skip to content

Instantly share code, notes, and snippets.

@Aloxaf
Created October 13, 2018 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aloxaf/57198521aec46ce2e270d85a19ea340b to your computer and use it in GitHub Desktop.
Save Aloxaf/57198521aec46ce2e270d85a19ea340b to your computer and use it in GitHub Desktop.
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