E0308
rust
type_error
ai_generated
true
error[E0308]: mismatched types: expected `usize`, found `f64`
ID: rust/e0308-expected-usize-found-float
92%Fix Rate
88%Confidence
1Evidence
2023-06-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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.htmlWorkarounds
-
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;`
-
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;`
-
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;`
中文步骤
Use `as usize` to convert f64 to usize, ensuring the value is non-negative and within range: `let index = value as usize;`
Use `f64::round()` or `f64::floor()` before casting: `let index = value.round() as usize;`
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:
-
45% fail
Truncation may cause logic errors; the compiler allows it but the behavior is undefined for negative or NaN values.
-
100% fail
Rust requires explicit conversion; this approach is syntactically invalid.
-
60% fail
If the value comes from a computation or input that yields f64, the type mismatch persists.