Possible out of date guessing_game code in rust book?


Hi guys,

This is my first real experience with rust, and while going through the book, I noticed that the “guessing_game” example seems wrong.

When I run it, it prints “You guessed X” where X is the length of my guess, and not the guess I made. Has the IO API changed to return the number of bytes read instead of the bytes themselves?

Just in case I’ve transcribed something wrong, here’s my code and an example:

$ cat src/main.rs 
use std::io;

fn main() {
    println!("Guess the number!");

    println!("Please input your guess.");

    let mut guess = String::new();

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

    println!("You guessed: {}", input);
$ cargo run
   Compiling guessing_game v0.1.0 (file:///tmp/guessing_game)
     Running `target/debug/guessing_game`
Guess the number!
Please input your guess.
You guessed: 6

If I replace the “input” on the last println! with “guess” all is well. Is this a problem with the book, or have I overlooked something? Thanks in advance!



Good catch. The example is wrong

read_line now returns the number of bytes read. This was fixed in https://github.com/rust-lang/rust/pull/25148


Fab! Thanks for the quick reply! It seemed like a simple oversight, but when learning something new it’s always best to check :smile: