Rust 猜游戏,阴影猜绑定错误

Rust 猜游戏,阴影猜绑定错误,rust,Rust,我正在遵循,但我被这段代码(页面中的最后一段代码)卡住了: 当我运行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() {

我正在遵循,但我被这段代码(页面中的最后一段代码)卡住了:

当我运行
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() {
                                                             ^

正确的语法是什么

出现语法错误,编译器消息将您的注意力引导到行中错误的位置以修复问题

parse
方法的计算结果为一个值。此表达式后面不应跟一个块,从而导致编译器报告的语法错误

您链接到的示例在赋值和调用
parse
之间有关键字
匹配。
match
关键字接受表达式,并根据表达式的值进行分支。该块包含分支模式和表达式。在这种情况下,它还将
结果
分解为
u32
u32::Err

下面是一个示例,为了清晰起见,它将解析和匹配分开

// 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,
};

调用
guess.trim().parse()之前忘记添加
match
关键字 这条线应该是这样的:
let guess:u32=匹配guess.trim().parse(){…


来源:

你忘记了分配
=
后的
匹配项
。只需再将其与原始代码进行比较。一个差分工具将非常有价值地指出差异。有两个版本和命令行版本。@LukasKalbertodt谢谢!我现在觉得很愚蠢…@rpadovani这发生在我们当中最好的一个;)但是,请检查在询问StackOverflow之前,对代码进行优化并进行最少的思考可以避免类似这样的无益问题。只需继续编码并从学习Rust!:3尼斯解释中获得乐趣。但是,这是一个解析错误,解析器不关心
parse
的返回类型。实际上,
guess.trim().parse()
expression后面不能跟代码块,但是类型也不重要。也许您可以从答案中删除该部分。。。
// 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,
};