Created
July 7, 2019 08:54
-
-
Save wingyplus/96c801ab94cb3a45e2a08803cd5d39cf to your computer and use it in GitHub Desktop.
Guessing Game from Rust book https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html
This file contains 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
package main | |
import ( | |
"bufio" | |
"fmt" | |
"math/rand" | |
"os" | |
"strconv" | |
"strings" | |
"time" | |
) | |
func main() { | |
rand.Seed(time.Now().UnixNano()) | |
fmt.Println("Guess the number!") | |
// rust can generate range [1, 101). So in go we can fix this | |
// by +1 after number was generated. | |
secretNumber := rand.Intn(101) + 1 | |
fmt.Println("The secret number is:", secretNumber) | |
gameLoop: | |
for { | |
fmt.Println("Please input your guess") | |
r := bufio.NewReader(os.Stdin) | |
line, _, err := r.ReadLine() | |
if err != nil { | |
panic("Failed to read line") | |
} | |
guess, err := strconv.Atoi(strings.TrimSpace(string(line))) | |
if err != nil { | |
continue | |
} | |
fmt.Println("You guessed:", guess) | |
switch { | |
case guess < secretNumber: | |
fmt.Println("Too small!") | |
case guess > secretNumber: | |
fmt.Println("Too big!") | |
case guess == secretNumber: | |
fmt.Println("You win!") | |
// in Go, break statement can terminated switch execution. This can fix by adding label above of loop. | |
break gameLoop | |
} | |
} | |
} |
This file contains 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 rand::Rng; | |
use std::cmp::Ordering; | |
use std::io; | |
fn main() { | |
println!("Guess the number!"); | |
let secret_number = rand::thread_rng().gen_range(1, 101); | |
println!("The secret number is: {}", secret_number); | |
loop { | |
println!("Please input your guess"); | |
let mut guess = String::new(); | |
io::stdin() | |
.read_line(&mut guess) | |
.expect("Failed to read line"); | |
let guess: u32 = match guess.trim().parse() { | |
Ok(num) => num, | |
Err(_) => continue, | |
}; | |
println!("You guessed: {}", guess); | |
match guess.cmp(&secret_number) { | |
Ordering::Less => println!("Too small!"), | |
Ordering::Greater => println!("Too big!"), | |
Ordering::Equal => { | |
println!("You win!"); | |
break; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment