Pass if block as parameter
I'm trying to write a small test program in Rust, and since almost anything can be an expression in that language, including instructions if
, I wanted to pass a block if-else
as a parameter to println!
, for example:
println!("{} {} {}", i.name, if v>0 {"owes"} else{"must receive"}, if v<0 {-v} else{v});
but I am getting this error:
src/main.rs:34:38: 34:39 error: mismatched types:
expected `f32`,
found `_`
(expected f32,
found integral variable) [E0308]
src/main.rs:34 println!("{} {} {}", i.name, {if v>0 {"owes"} else{"must receive"}}, if v<0 {-v} else{v});
And the same error with another block if-else
I missed. As far as I understood the concept, this should work because these blocks if-else
are expressions that return the latest values ββin each branch.
Any help would be appreciated, thanks in advance.
+3
source to share