【问题标题】:How to convert a u32 constant to i32 constant without unsafe in Rust?如何在 Rust 中将 u32 常量转换为 i32 常量而不安全?
【发布时间】:2021-06-04 15:47:29
【问题描述】:

我正在尝试从现有的 u32 常量定义一个新的 i32 常量,以便在匹配表达式中使用,因为 io::Error::raw_os_error() 返回一个 i32,但 winapi 错误常量是 u32。

在下面的代码示例中,现有的 u32 常量将是 ERROR_NO_MORE_FILES

我发现这样做的唯一方法是使用不安全的块。

我是 Rust 新手,那么有没有办法将 u32 转换为 i32 常量而不会不安全?

use std::io::Error;
use std::convert::TryFrom;

const ERROR_NO_MORE_FILES: u32 = 18; // defined in winapi winerror
const ERROR_NO_MORE_FILES_I32: i32 = unsafe { ERROR_NO_MORE_FILES as i32 };
// Attempted to use safe conversion does not compile:
// error[E0015]: calls in constants are limited to constant functions, tuple structs and tuple variants
// const ERROR_NO_MORE_FILES_I32: i32 = i32::try_from(ERROR_NO_MORE_FILES).unwrap();

fn main() -> Result<(), Error> {
    let err = Error::last_os_error();
    match err.raw_os_error() { // an i32
        Some(ERROR_NO_MORE_FILES_I32)  => { println!("No more files..."); },
        Some(_) => return Err(err),
        _  => {}
    }
    Ok(())
}


【问题讨论】:

  • 您拥有的unsafe 块已经不需要了。当你编译时,Rust 甚至会告诉你。 play.rust-lang.org/…

标签: rust constants


【解决方案1】:

正如@loganfsmyth 指出的那样,在这种情况下我不需要不安全的。我不确定我是如何错过警告的(可能应该这么晚才停止编码)......

这编译得很好:

const ERROR_NO_MORE_FILES: u32 = 18; // defined in winapi winerror
const ERROR_NO_MORE_FILES_I32: i32 = ERROR_NO_MORE_FILES as i32;

fn main() {
    println!("{}", ERROR_NO_MORE_FILES_I32);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多