E0080
rust
type_error
ai_generated
true
错误[E0080]:将 `bool` 转换为 `char` 是未定义行为
error[E0080]: it is undefined behavior to cast `bool` to `char`
ID: rust/e0080-invalid-cast-from-bool-to-char
95%修复率
86%置信度
1证据数
2023-08-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| rustc 1.65.0 | active | — | — | — |
| rustc 1.70.0 | active | — | — | — |
| rustc 1.76.0 | active | — | — | — |
根因分析
将 bool 转换为 char 是未定义行为,因为 bool 只有值 0 和 1,但 char 要求有效的 Unicode 标量值(0x0 到 0x10FFFF,不包括代理项)。
English
Casting a bool to char is undefined behavior because bool has values 0 and 1, but char requires valid Unicode scalar values (0x0 to 0x10FFFF, excluding surrogates).
官方文档
https://doc.rust-lang.org/error_codes/E0080.html解决方案
-
使用 match 进行显式转换:`let c = if b { '1' } else { '0' };` -
使用 `char::from_digit(b as u32, 10).unwrap_or('0')` 获取数字字符。 -
先转换为 u8:`let c = (b as u8 + b'0') as char;` 用于 ASCII 数字。
无效尝试
常见但无效的做法:
-
95% 失败
Rust's as cast is not allowed for bool-to-char because it's UB. The compiler rejects it.
-
80% 失败
Transmute is unsafe and still UB. It might compile but is undefined behavior.
-
90% 失败
There is no From<bool> impl for char. This won't compile.