0

I could not understand this code. How comes -a yields different result from -7?

fn main() {
    let a: i32 = 7; // or any other integer type
    let b = 4;
                
    assert_eq!((-a).rem_euclid(b), 1);
    assert_eq!(-7_i32.rem_euclid(4), -3);
    assert_eq!(-a, -7_i32);
}

Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=3147fbbf7aeeeff5510522f9af2d12f2

2
  • 2
    It is because in second assertion you negate the result, in first one you negate the operand Commented Jul 3, 2020 at 19:13
  • 1
    @yolenoyer Because it's a basic question that shows no research and is not useful to others. Playing around with the placement of the parentheses would have shown the difference pretty quickly. Commented Jul 3, 2020 at 23:18

1 Answer 1

4

It's because -7_i32.rem_euclid(4) == -(7_i32.rem_euclid(4)). The unary negation has lower precedence than the method call.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.