Skip to content

Instantly share code, notes, and snippets.

@BruJu
Last active Dec 3, 2019
Embed
What would you like to do?
Rust first program
use std::cmp::Ordering;
use std::io;
use rand::Rng;
use std::io::Write;
use std::format;
// My first program in rust to test the language
// Kept to laught at myself in several months
// Inspired from the guessing game of the Rust book
trait Animal {
fn talk(&self) -> String;
}
struct Sheep { }
struct Cat { name: &'static str }
impl Animal for Sheep {
fn talk(&self) -> String {
format!("{}", "Beeeeh")
}
}
impl Cat {
fn new(name: &'static str) -> Cat {
Cat {name: name}
}
}
impl Animal for Cat {
fn talk(&self) -> String {
format!("Maou I am {}", self.name)
}
}
fn main() {
let chicken = '🐔';
println!("Before playing let's draw a chicken {}", chicken);
let sheep = Sheep{};
println!("What does the sheep says ? {}", sheep.talk());
println!("What does the cat says ? {}", Cat::new("Felix").talk());
let (nb_of_iter, guessed_numbers) = guessing_game();
println!("Found {} in {} iterations", guessed_numbers, nb_of_iter);
}
fn guessing_game() -> (i32, u32) {
println!("== THE GUESSING GAME ==");
let secret_number = rand::thread_rng().gen_range(1, 10);
let mut nb_of_iterations = 0;
loop {
print!("Press your input : ");
io::stdout().flush();
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Error when reading line");
match guess.trim().parse::<u32>() {
Ok(num) => {
nb_of_iterations = nb_of_iterations + 1;
print!("You gave the number {} ", num);
match num.cmp(&secret_number) {
Ordering::Less => println!("and its too low"),
Ordering::Greater => println!("and its too high"),
Ordering::Equal => {
println!("and it's a GG WP EZPZ");
break;
},
}
},
Err(z) => println!("Are you drunk ? {}", z),
};
}
return (nb_of_iterations, secret_number);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment