Is this behaviour desirable?


#1

The following bit me pretty hard today (at runtime!!)

fn main() {
    let s = -1; 
    let u: usize = 0; 
    let _ = u == s+1;
}

This triggers:

thread '<main>' panicked at 'arithmetic operation overflowed', <anon>:4

http://is.gd/zHJIth

I think understand why: s is being inferred as type usize because of the comparison. However by saying s = -1 I thought I was pretty clear about the fact that I would never want s to be unsigned. I guess the compiler should reject this, right? I can file an issue if needed.


#2

It would be consistent with the fact that

let s: usize = -1;

is rejected:

<anon>:2:20: 2:22 error: unary negation of unsigned integers may be removed in the future
<anon>:2     let s: usize = -1;
                            ^~

#3

This is purposeful.

[quote]There’s a lot of concern that having +, -, and *
overflow by default is incorrect - it’s a source of many security
vulnerabilities. Let’s try changing the default to being checked and
measure the impact on performance and code size.[/quote]


#4

Sorry if I didn’t make myself clear enough. What bothers me is not that overflow panics by default. It’s a nice design decision. My problem is that when I write “let s = -1”, I do not want s to be inferred as an unsigned type!


#5

you cant add two different integer types, and if you do not want it to be inferred, then type it explicitly.


#6

@mdup FYI, I don’t think any of the responses to your topic are correct. You’re correct that it’s extremely odd that s can be inferred to be usize when explicitly specifying usize would be an error. Probably a bug; too late to make it an error now, but it could be linted…


#7

Yeah, that’s kinda weird, indeed.


#8

It is a bug.


#9

Wow,

fn main() {
    let x = -1;
    let y: u8 = x;
    
    println!("{} {}", x, y);
}

Output:

255 255
Program ended.

#10

Now that’s a bug I can get behind! (To be fixed)