E0308
rust
type_error
ai_generated
true
错误[E0308]:类型不匹配:期望 `usize`,得到 `f64`
error[E0308]: mismatched types: expected `usize`, found `f64`
ID: rust/e0308-expected-usize-found-float
92%修复率
88%置信度
1证据数
2023-06-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| rustc 1.70.0 | active | — | — | — |
| rustc 1.75.0 | active | — | — | — |
| rustc 1.82.0 | active | — | — | — |
根因分析
在需要无符号整数索引的位置(如数组索引或切片操作)使用了浮点数。
English
Assigning or passing a floating-point value where an unsigned integer index is required, often in array indexing or slice operations.
官方文档
https://doc.rust-lang.org/error_codes/E0308.html解决方案
-
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;`
无效尝试
常见但无效的做法:
-
45% 失败
Truncation may cause logic errors; the compiler allows it but the behavior is undefined for negative or NaN values.
-
100% 失败
Rust requires explicit conversion; this approach is syntactically invalid.
-
60% 失败
If the value comes from a computation or input that yields f64, the type mismatch persists.