猜谜游戏的问题

extern crate rand;

use std::io;

use std::cmp::Ordering;

use rand::Rng;



fn main() {

    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(1, 101);


    println!("The secret number is: {}", secret_number);

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

    let mut guess = String::new();

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

    println!("You guessed: {}", guess);

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

但这给了我一个错误:
src\main.rs:26:21: 26:35 error: mismatched types:
 expected `&collections::string::String`,
    found `&_`
(expected struct `collections::string::String`,
    found integral variable) [E0308]
src\main.rs:26     match guess.cmp(&secret_number) {
                                   ^~~~~~~~~~~~~~

这是什么原因,我该怎么解决?

最佳答案

stdin的用户输入是一个字符串。而你从rand得到的数字是一个u32。尝试在to_string上使用secret_number
match guess.cmp(&secret_number.to_string())

关于rust - Rust 1.3.0中的猜谜游戏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32665342/

10-08 21:11