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


1 answer


v

probably is f32

, which means the comparison v>0

has a type error.
Try v>0.0

and instead v<0.0

.



+2


source







All Articles