当前位置:   article > 正文

《The Rust Programming Language》的Rust 学习 1

the rust programming language

最近开始学Rust了,主要看《The Rust Programming Language》,个人感觉《Rust by example》不适合小白,到结构体哪里的题就已经不会做了。慢慢更新这个帖子。

2.Programming a Guessing Game

作者给的代码

   let mut guess = String::new();

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

    let guess: u32 = guess.trim().parse().expect("Please type a number!");

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

    match guess.cmp(&secret_number) {
        Ordering::Less => println!("Too small!"),
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

我的想法是把secret_number转成String和guess比较

    println!("{}",&(&secret_number).to_string());
    let mut guess = String::new();
    io::stdin()
        .read_line(&mut guess)
        .expect("input error");
    //let guess : u32 = guess.trim().parse().expect("");
    println!("You guessed: {}", guess);

    match guess.cmp(&(&secret_number).to_string()) {
        Ordering::Less => println!("Too small!"),
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

虽然可以编译过,但是运行结果不对
在这里插入图片描述

用 gdb调试了一下
display 发现 两个string缺一个/n
在这里插入图片描述
最终改写为

        let secret_number = rand::thread_rng().gen_range(1, 101);
        let mut secret_number : String = secret_number.to_string();
        secret_number.push_str("\n");
    ........
        match guess.cmp(&secret_number) {
                  Ordering::Less => println!("Too small!"),
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

成功了
在这里插入图片描述
之前没有注意这个

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

这一行输出有空格。。。

文章中也说了输入带空格的问题

We bind guess to the expression guess.trim().parse(). The guess in the expression refers to the original guess that was a String with the input in it. The trim method on a String instance will eliminate any whitespace at the beginning and end. Although u32 can contain only numerical characters, the user must press enter to satisfy read_line. When the user presses enter, a newline character is added to the string. For example, if the user types 5 and presses enter, guess looks like this: 5\n. The \n represents “newline,” the result of pressing enter. The trim method eliminates \n, resulting in just 5.
所以在作者的代码

  let guess: u32 = guess.trim().parse().expect("Please type a number!");
  • 1

trim()删除 \n
parse()将 String类型的变量转化为指定类型

因此简单点就行

match guess.trim().cmp(&(&secret_number).to_string()) {
     Ordering::Less => println!("Too small!"),
  • 1
  • 2
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/702804
推荐阅读
相关标签
  

闽ICP备14008679号