E0080 rust type_error ai_generated true

error[E0080]: it is undefined behavior to cast `bool` to `char`

ID: rust/e0080-invalid-cast-from-bool-to-char

Also available as: JSON · Markdown · 中文
95%Fix Rate
86%Confidence
1Evidence
2023-08-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
rustc 1.65.0 active
rustc 1.70.0 active
rustc 1.76.0 active

Root Cause

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).

generic

中文

将 bool 转换为 char 是未定义行为,因为 bool 只有值 0 和 1,但 char 要求有效的 Unicode 标量值(0x0 到 0x10FFFF,不包括代理项)。

Official Documentation

https://doc.rust-lang.org/error_codes/E0080.html

Workarounds

  1. 95% success Use explicit conversion with a match: `let c = if b { '1' } else { '0' };`
    Use explicit conversion with a match: `let c = if b { '1' } else { '0' };`
  2. 90% success Use `char::from_digit(b as u32, 10).unwrap_or('0')` if you want digit characters.
    Use `char::from_digit(b as u32, 10).unwrap_or('0')` if you want digit characters.
  3. 85% success Convert to u8 first: `let c = (b as u8 + b'0') as char;` for ASCII digits.
    Convert to u8 first: `let c = (b as u8 + b'0') as char;` for ASCII digits.

中文步骤

  1. 使用 match 进行显式转换:`let c = if b { '1' } else { '0' };`
  2. 使用 `char::from_digit(b as u32, 10).unwrap_or('0')` 获取数字字符。
  3. 先转换为 u8:`let c = (b as u8 + b'0') as char;` 用于 ASCII 数字。

Dead Ends

Common approaches that don't work:

  1. 95% fail

    Rust's as cast is not allowed for bool-to-char because it's UB. The compiler rejects it.

  2. 80% fail

    Transmute is unsafe and still UB. It might compile but is undefined behavior.

  3. 90% fail

    There is no From<bool> impl for char. This won't compile.