Skip to content

Error message on casting negative numbers to usize is quite unhelpful #76413

Closed
@Disasm

Description

@Disasm

Code:

fn syscall(nr: usize) -> usize {
    match nr {
        1 => (-1) as usize,
        _ => -1 as usize,
    }
}

fn syscall_i(nr: usize) -> isize {
    match nr {
        1 => (-1) as isize,
        _ => -1 as isize,
    }
}

fn main() {
    let rc = syscall(42);
    println!("result: {}", rc);
    
    let rc = syscall_i(42);
    println!("result: {}", rc);
}

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

Error message:

error[E0600]: cannot apply unary operator `-` to type `usize`
 --> src/main.rs:3:14
  |
3 |         1 => (-1) as usize,
  |              ^^^^ cannot apply unary operator `-`
  |
  = note: unsigned values cannot be negated

error[E0600]: cannot apply unary operator `-` to type `usize`
 --> src/main.rs:4:14
  |
4 |         _ => -1 as usize,
  |              ^^ cannot apply unary operator `-`
  |
  = note: unsigned values cannot be negated

Somehow, in one case this 1 in the -1 expression is unsigned, but in the other case it is signed and everything is fine.

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-papercutDiagnostics: An error or lint that needs small tweaks.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions