赞
踩
最近开始学Rust了,主要看《The Rust Programming Language》,个人感觉《Rust by example》不适合小白,到结构体哪里的题就已经不会做了。慢慢更新这个帖子。
作者给的代码
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!"),
我的想法是把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!"),
虽然可以编译过,但是运行结果不对
用 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!"),
成功了
之前没有注意这个
println!("You guessed: {}", guess);
这一行输出有空格。。。
文章中也说了输入带空格的问题
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!");
trim()删除 \n
parse()将 String类型的变量转化为指定类型
因此简单点就行
match guess.trim().cmp(&(&secret_number).to_string()) {
Ordering::Less => println!("Too small!"),
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。