DEV Community

Hirokazu Hirono
Hirokazu Hirono

Posted on

`-100_i32.abs()` outputs `-100` ...... What?

Sometimes I forgot that this occurs in Rust.

But in Rust, method calls have a higher precedence than unary prefix operators.

println!("{}", -100_i32.abs()); // -100

Alt Text

so if 100 is what we want as an output, we need to put the parentheses around -100_i32.

println!("{}", (-100_i32).abs()); // 100

Top comments (0)