Is this behaviour desirable?


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

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.


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;


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]


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!


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


@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…


Yeah, that’s kinda weird, indeed.


It is a bug.



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


255 255
Program ended.


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