Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing if block as parameter

I'm trying to write a small test program in Rust, and, as almost everything can be an expression in this language, including if statements, I wanted to pass an if-else block as a parameter to the println! macro, like this:

println!("{} {} {}", i.name, if v>0 {"owes"} else{"must receive"}, if v<0 {-v} else{v});

but I'm 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 the other if-else block, which I've omitted. As far as I've understood the concept, this should work because this if-else blocks are expressions which return the last values in each branch.

Any help will be appreciated, thanks in advance.

like image 899
Dani Avatar asked Mar 17 '26 20:03

Dani


1 Answers

v is probably an f32, which means the comparison v>0 has a type error.
Try v>0.0 and v<0.0 instead.

like image 188
Veedrac Avatar answered Mar 20 '26 15:03

Veedrac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!