guessing game - adilsoncarvalho/rust.n.go GitHub Wiki

Pull request: https://github.com/adilsoncarvalho/rust.n.go/pull/2

Result after compilation

  • Go: 2.1M
  • Rust: 502k

Comparing rust and go code

matchers in rust

The matchers in rust offer an elegant way to compare values

// rust

match guess.cmp(&secret_number) {
    Ordering::Less => println!("Too small!"),
    Ordering::Greater => println!("Too big!"),
    Ordering::Equal => {
        println!("You win!");
        break;
    }
}
// go

if guessInt < secretNumber {
    fmt.Println("Too small!")
} else if guessInt > secretNumber {
    fmt.Println("Too big!")
} else {
    fmt.Println("You win!")
    break
}

Shadowing variables in rust

I cannot say that I am a fan of it. In all these years in this vital industry, this shadowing feature is something we learned to be not the best practice while coding. One variable should remain of the same type, and if possible, with the same value within the code block or context.

// rust

let mut guess = String::new();

// some funky code

let guess: u32 = ...

Dealing with errors

// rust

io::stdin()
  .read_line(&mut guess)
  .expect("Failed to read line");

// or

match io::stdin()
  .read_line(&mut guess) {
    Ok(val) => val,
    Err(_) => {
      println!("Failed to read line");
      return;
    }
  }
// go

_, err := fmt.Scanln(&guess)

if err != nil {
    fmt.Println("Failed to read line")
    os.Exit(1)
}