E0308 rust type_error ai_generated true

error[E0308]: mismatched types: expected `usize`, found `f64`

ID: rust/e0308-expected-usize-found-float

Also available as: JSON · Markdown · 中文
92%Fix Rate
88%Confidence
1Evidence
2023-06-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
rustc 1.70.0 active
rustc 1.75.0 active
rustc 1.82.0 active

Root Cause

Assigning or passing a floating-point value where an unsigned integer index is required, often in array indexing or slice operations.

generic

中文

在需要无符号整数索引的位置(如数组索引或切片操作)使用了浮点数。

Official Documentation

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

Workarounds

  1. 85% success Use `as usize` to convert f64 to usize, ensuring the value is non-negative and within range: `let index = value as usize;`
    Use `as usize` to convert f64 to usize, ensuring the value is non-negative and within range: `let index = value as usize;`
  2. 80% success Use `f64::round()` or `f64::floor()` before casting: `let index = value.round() as usize;`
    Use `f64::round()` or `f64::floor()` before casting: `let index = value.round() as usize;`
  3. 90% success If the value is from user input or computation, parse or compute it as `usize` directly: `let index: usize = some_usize_source;`
    If the value is from user input or computation, parse or compute it as `usize` directly: `let index: usize = some_usize_source;`

中文步骤

  1. Use `as usize` to convert f64 to usize, ensuring the value is non-negative and within range: `let index = value as usize;`
  2. Use `f64::round()` or `f64::floor()` before casting: `let index = value.round() as usize;`
  3. If the value is from user input or computation, parse or compute it as `usize` directly: `let index: usize = some_usize_source;`

Dead Ends

Common approaches that don't work:

  1. 45% fail

    Truncation may cause logic errors; the compiler allows it but the behavior is undefined for negative or NaN values.

  2. 100% fail

    Rust requires explicit conversion; this approach is syntactically invalid.

  3. 60% fail

    If the value comes from a computation or input that yields f64, the type mismatch persists.