Created
May 31, 2019 02:43
-
-
Save nenodias/be695db7bc5e03cf449e6e1f339ed03d to your computer and use it in GitHub Desktop.
Example Rust Input data on terminal
This file contains hidden or 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::io; | |
| fn input(mensagem: &'static str) -> String { | |
| println!("{}", mensagem); | |
| let mut input: String = "".to_string(); | |
| io::stdin().read_line(&mut input).unwrap(); | |
| input.truncate(input.len() - 1);//Remove \n | |
| input | |
| } | |
| //For numbers, bools | |
| macro_rules! input_or { | |
| ($msg:expr, $default:expr) => { | |
| match input($msg).parse(){ | |
| Ok(valor) => valor, | |
| Err(_) => $default | |
| }; | |
| }; | |
| } | |
| fn exemplo_1() { | |
| let mut nome: String = "".to_string(); | |
| println!("Qual o seu nome:"); | |
| io::stdin().read_line(&mut nome).unwrap(); | |
| println!("Olá {}", nome); | |
| } | |
| fn exemplo_2(){ | |
| let nome = input("Qual o seu nome:"); | |
| let idade = match input("Qual a sua idade:").parse::<i32>(){ | |
| Ok(valor) => valor, | |
| Err(_) => 0 | |
| }; | |
| println!("Olá {}, voce tem {}", nome, idade); | |
| } | |
| fn exemplo_3() { | |
| let nome = input("Qual o seu nome:"); | |
| let idade = input_or!("Qual a sua idade:", 0); | |
| println!("Olá {}, voce tem {}", nome, idade); | |
| let curte_rock = input_or!("Você curte rock:", false); | |
| println!("Vocẽ curte: {}", curte_rock); | |
| } | |
| fn main() { | |
| exemplo_3(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment