我正在关注Rust tutorial,但我坚持使用此代码(页面中的最后一个代码段):
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);
loop {
println!("Please input your guess");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
}
println!("You guessed: {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
当我运行cargo run
时出现以下错误:
src/main.rs:23:47: 23:48 error: expected one of `.`, `;`, or an operator, found `{`
src/main.rs:23 let guess: u32 = guess.trim().parse() {
^
什么是正确的语法?
答案 0 :(得分:4)
存在语法错误,并且编译器消息将您的注意力引导到该行的错误位置以解决问题。
parse
方法求值为一个值。该表达式后面不应该跟一个块,导致编译器报告语法错误。
https://doc.rust-lang.org/std/string/struct.String.html#method.parse
您关联的示例在分配和调用match
之间具有关键字parse
。 match
关键字根据表达式的值获取表达式和分支。该块包含分支模式和表达式。在这种情况下,它还将Result
解构为u32
或u32::Err
。
https://doc.rust-lang.org/book/match.html
下面是一个分析解析和匹配的示例,以便清晰。
// Store result of parsing in a variable
let parse_result = guess.trim().parse();
// Destructure the result
let guess: u32 = match parse_result {
// If parse succeeded evaluate to the number
Ok(num) => num,
// If parse failed repeat the loop
Err(_) => continue,
};
答案 1 :(得分:0)
您在致电match
之前忘记添加guess.trim().parse()
关键字
该行应如下所示:
let guess : u32 = match guess.trim().parse() {...
来源:https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html