Skip to content

Instantly share code, notes, and snippets.

@nenodias
Created May 31, 2019 02:43
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 nenodias/be695db7bc5e03cf449e6e1f339ed03d to your computer and use it in GitHub Desktop.
Save nenodias/be695db7bc5e03cf449e6e1f339ed03d to your computer and use it in GitHub Desktop.
Example Rust Input data on terminal
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