If statement 结果和if/else/return语句E0308错误
为什么下面的代码在编译时会引发错误If statement 结果和if/else/return语句E0308错误,if-statement,rust,return,If Statement,Rust,Return,为什么下面的代码在编译时会引发错误 fn test(n: i32) -> Result<i32, &'static str> { if n == 0 { Err("error") } Ok(n + 1) } 使用return语句: fn test(n: i32) -> Result<i32, &'static str> { if n == 0 { Err("error")
fn test(n: i32) -> Result<i32, &'static str> {
if n == 0 {
Err("error")
}
Ok(n + 1)
}
return
语句:
fn test(n: i32) -> Result<i32, &'static str> {
if n == 0 {
Err("error")
}
else {
Ok(n + 1)
}
}
fn test(n: i32) -> Result<i32, &'static str> {
if n == 0 {
return Err("error");
}
Ok(n + 1)
}
fn测试(n:i32)->结果想象一下这个简化的代码:
fn test() -> i32{
{ 1 }
2
}
此操作失败,出现以下错误:
error[E0308]: mismatched types
--> src/main.rs:2:11
|
2 | { 1 }
| ^ expected (), found integral variable
|
= note: expected type `()`
found type `{integer}`
这是因为在Rust中,完整语句必须具有类型()
。如果要忽略某个值,只需添加一个
将值转换为语句,并将类型更改为()
放弃该值
此代码编译:
fn test() -> i32{
{ 1; }
2
}
您的示例与此类似,但是if
使事情更有趣。如果你写:
fn test(c: bool) -> i32{
if c { 1 }
2
}
与前面一样,它将失败,因为第一条语句的类型不同于()
。添加一个代码>解决了这个问题:
fn test(c: bool) -> i32{
if c { 1; }
2
}
编写else
也可以编译,因为这样函数中只有一条语句,其类型与函数的返回类型匹配:
fn test(c: bool) -> i32{
if c { 1 }
else { 2 }
}
请注意,两个分支必须具有相同的类型,并且没有代码>中的任意一个
添加return
也会起作用,因为return语句定义为()
,因此任何一个都将编译:
fn test1(c: bool) -> i32{
if c { return 1; }
2
}
fn test2(c: bool) -> i32{
if c { return 1 }
2
}
fn test3(c: bool) -> i32{
if c { return 1; }
else { 2 }
}
fn test4(c: bool) -> i32{
if c { return 1; }
else { return 2; }
}
注意是如何工作的
在这些return
语句中实际上是可选的,因为它已经是()
想象一下这个简化的代码:
fn test() -> i32{
{ 1 }
2
}
此操作失败,出现以下错误:
error[E0308]: mismatched types
--> src/main.rs:2:11
|
2 | { 1 }
| ^ expected (), found integral variable
|
= note: expected type `()`
found type `{integer}`
这是因为在Rust中,完整语句必须具有类型()
。如果要忽略某个值,只需添加一个
将值转换为语句,并将类型更改为()
放弃该值
此代码编译:
fn test() -> i32{
{ 1; }
2
}
您的示例与此类似,但是if
使事情更有趣。如果你写:
fn test(c: bool) -> i32{
if c { 1 }
2
}
与前面一样,它将失败,因为第一条语句的类型不同于()
。添加一个代码>解决了这个问题:
fn test(c: bool) -> i32{
if c { 1; }
2
}
编写else
也可以编译,因为这样函数中只有一条语句,其类型与函数的返回类型匹配:
fn test(c: bool) -> i32{
if c { 1 }
else { 2 }
}
请注意,两个分支必须具有相同的类型,并且没有代码>中的任意一个
添加return
也会起作用,因为return语句定义为()
,因此任何一个都将编译:
fn test1(c: bool) -> i32{
if c { return 1; }
2
}
fn test2(c: bool) -> i32{
if c { return 1 }
2
}
fn test3(c: bool) -> i32{
if c { return 1; }
else { 2 }
}
fn test4(c: bool) -> i32{
if c { return 1; }
else { return 2; }
}
注意是如何工作的在这些return
语句中,code>实际上是可选的,因为它已经是()
类型了,我相信您的问题已经由和的答案回答了。如果你不同意,请用你的问题来解释不同之处。否则,我们可以将此问题标记为已回答。我相信您的问题已由和的答案回答。如果你不同意,请用你的问题来解释不同之处。否则,我们可以将此问题标记为已回答。