![](/img/trans.png)
[英]How to resolve mismatched types error around reference that involves getting a value from a struct in Rust
[英]Returning a value from within an if statement has a “mismatched types” error
在下面的函数中,我匹配&str
的第一个完整字符,如果它是*
, -
或_
以及返回的是那些字符,那么我想用_
臂检查该字符是否为空格,否则返回'a'
。
fn print_character(text: &str) {
let character: char = match text.chars().nth(0).unwrap() {
ch @ '*' | ch @ '-' | ch @ '_' => ch,
ch @ _ => {
if !ch.is_whitespace() {
return 'a';
}
' '
}
};
println!("{}", character);
}
当我运行代码时,出现以下错误:
error[E0308]: mismatched types
--> src/main.rs:6:24
|
6 | return 'a';
| ^^^ expected (), found char
|
= note: expected type `()`
found type `char`
您不希望在这里返回,也不想在函数中返回。 只需使用'a'
作为表达式。 您还需要将空格字符作为else分支,而不是独立存在。
if !ch.is_whitespace() {
'a'
} else {
' '
}
else
if
是一个表达式,它必须求值。 该值需要一个确定的类型。 有时不能是char
,有时不能是其他char
。 如果您只是这样做:
if !ch.is_whitespace() {
'a'
}
if
测试失败, if
表达式会得出什么结果? 语言不只是求值一个任意的char
值,而是只需要一个else
分支。 如果您不想将if
用作表达式,而只是将其用于副作用,则可以省略else
。 在那种情况下,它仍然是一个表达式,但是它的值是()
(与测试是否通过无关),并且您需要以一个语句结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.