rust-lang/rust-clippy

`cast_lossless` not triggered by `char as u32`

Open

#14.469 aperta il 25 mar 2025

Vedi su GitHub
 (4 commenti) (1 reazione) (1 assegnatario)Rust (1391 fork)batch import
C-bugI-false-negativegood first issue

Metriche repository

Star
 (10.406 star)
Metriche merge PR
 (Merge medio 16g 6h) (79 PR mergiate in 30 g)

Descrizione

Summary

Casting a char to a u32 is lossless, but the cast_lossless lint doesn't cover it.

Lint Name

cast_lossless

Reproducer

I tried this code:

#![deny(clippy::cast_lossless)]

fn main() {
    let _ = '|' as u32;
}

Playground

I expected to see this happen: Compiler error

error: casts from `char` to `u32` can be expressed infallibly using `From`
 --> src/main.rs:4:13
  |
4 |     let _ = '|' as u32;
  |             ^^^^^^^^^^
  |
  = help: an `as` cast can become silently lossy if the types change in the future
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cast_lossless
note: the lint level is defined here
 --> src/main.rs:1:9
  |
1 | #![deny(clippy::cast_lossless)]
  |         ^^^^^^^^^^^^^^^^^^^^^
help: use `u32::from` instead
  |
4 |     let _ = u32::from('|');
  |             ~~~~~~~~~~~~~~

Instead, this happened:

The code compiled without any issues.

Version

rustc 1.87.0-nightly (1aeb99d24 2025-03-19)
binary: rustc
commit-hash: 1aeb99d248e1b0069110cb03c6f1dcc7b36fd7f3
commit-date: 2025-03-19
host: x86_64-unknown-linux-gnu
release: 1.87.0-nightly
LLVM version: 20.1.0

(also on stable via playground)

Guida contributor