if 和else 分支的值类型是不相容的,同时 Rust 也准确地指出在程序中的何处发现的这个问题: $ cargo run Compiling branches v0.1.0 (file:///projects/branches) error[E0308]: `if` and `else` have incompatible types --> src/main.rs:4:44 | 4 | let number = if condition { 5 } else { "...
看起来和别的语言也没啥不同,但是rust的特点就是特安全,所以你这里的条件如果不是一个布尔值是会直接报错的,比如 img_mismatched_types 另外,rust还允许赋值,毕竟if表达式中也有{}也就是花括号,允许返回值[3]。 img_d_value 当然,按老规矩这里的返回值得是相同的。 img_err_if_else_have_incompatible_types ...
("res = {}", res); } 上述代码会导致编译时的错误,因为if与else分支产生了不同类型的值。Rust在错误提示信息中指出了程序出现问题的地方: error[E0308]:`if`and`else`have incompatible types --> src\main.rs:10:9|7|letres =ifnum %2==0{ | ___-8| |123| | --- expected becauseofthis9...
fn main() { let condition = true; let number = if condition { 5 } else { "six" }; println!("The value of number is: {}", number); } 1. 2. 3. 4. 5. 6. 7. 会提示if and else have incompatible type. 循环语句 Rust中循环语句有三种类型,loop,while,for loop fn main() { l...
// error[E0308]: `if` and `else` have incompatible types fn return_animal(condition: bool) -> impl Animal { if condition { Dog { name: String::from("狗") } } else { Cat { name: String::from("猫") } } } 1. 2. 3. ...
fnmain(){lett=true;lets=ift{5}else{"6"};println!("{}",s)} 这种就会报错 ➜ fun git:(master)✗cargorun Compiling fun v0.1.0(/Users/Work/Code/Rust/student/fun)error[E0308]:`if`and`else`have incompatible types -->src/main.rs:6:9|3|lets=ift{|___-4||5||- expected because...
error[E0308]:`if`and`else`have incompatible types-->src/main.rs:6:9|3|/ifforward{4||v.iter()||---expected becauseofthis5||}else{6||v.iter().rev()||^^^expected struct`std::slice::Iter`,found struct`Rev`7||}||___-`if`and`else`have incompatible types|=note:expected...
("if case, false"); } // if let // error[E0308]: `if` and `else` have incompatible types // let number = if true {5} else {6.0}; let number = if true {5} else {6}; println!("if let: {}", number); if number % 4 == 0 { println!("if case, divisible by 4");...
fn factory(x:i32) -> impl Fn(i32) -> i32 {let num = 5;if x > 1{move |x| x + num} else {move |x| x - num}} 运行后,编译器报错: error[E0308]: `if` and `else` have incompatible types--> src/main.rs:15:9|12 | / if x > 1{13 | | move |x| x + num| | -...
简单地说(注意return):