Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I represent C's "unsigned negative" values in Rust code?

I'm calling the ResumeThread WinAPI function from Rust, using the winapi crate.

The documentation says:

If the function succeeds, the return value is the thread's previous suspend count.

If the function fails, the return value is (DWORD) -1.

How can I effectively check if there was an error?

In C:

if (ResumeThread(hMyThread) == (DWORD) -1) {
    // There was an error....
}

In Rust:

unsafe {
    if ResumeThread(my_thread) == -1 {
            // There was an error....
    }
}
the trait `std::ops::Neg` is not implemented for `u32`

I understand the error; but what is the best way to be semantically the same as the C code? Check against std::u32::MAX?

like image 665
TheNextman Avatar asked Jan 27 '26 01:01

TheNextman


1 Answers

In C, (type) expression is called a type cast. In Rust, you can perform a type cast by using the as keyword. We also give the literal an explicit type:

if ResumeThread(my_thread) == -1i32 as u32 {
    // There was an error....
}

I would personally use std::u32::MAX, potentially renamed, as they are the same value:

use std::u32::MAX as ERROR_VAL;

if ResumeThread(my_thread) == ERROR_VAL {
    // There was an error....
}

See also:

  • How do I convert between numeric types safely and idiomatically?
  • Is casting between integers expensive?
  • What is the difference between From::from and as in Rust?
  • In Rust, is "as" an operator?
  • How do I convert a boolean to an integer in Rust?
like image 135
Shepmaster Avatar answered Jan 29 '26 20:01

Shepmaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!