【发布时间】: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/…