我如何在 Rust 代码中表示 C 的 "unsigned negative" 值?

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

我打电话给 ResumeThread WinAPI function from Rust, using the winapi crate

文档说:

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

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

如何有效检查是否有错误?

在 C:

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

生锈:

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

我理解错误;但是在语义上与 C 代码相同的最佳方式是什么?检查 std::u32::MAX?

是的,std::u32::MAX!0u32(相当于 C ~0UL,强调它是给定类型的所有位集值这一事实)。

在 C 中,(type) expression 称为 类型转换 。在 Rust 中,您可以使用 as 关键字执行类型转换。我们还给文字一个明确的类型:

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

我个人会使用 std::u32::MAX,可能会重命名,因为它们的值相同:

use std::u32::MAX as ERROR_VAL;

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

另请参阅: