我有一个
Vec<f32>
,其值为零,我想将其转换为 NaN
。有没有办法通过使用条件语句就地修改 Vec
来做到这一点?
这是我迄今为止尝试过的:
let mut vector: Vec<f32> = vec![2.0, 0.0, 1.0, 3.0, -1.0, 5.0];
vector
.iter_mut()
.for_each(|v| if *v == 0.0 { f32::NAN } else { *v });
println!("{vector:?}");
但是编译器给了我这个错误:
error[E0308]: mismatched types
--> src/io/mod.rs:8:38
|
8 | .for_each(|v| if *v == 0.0 { f32::NAN } else { *v });
| ---------------^^^^^^^^--------------
| | |
| | expected `()`, found `f32`
| expected this to be `()`
error[E0308]: mismatched types
--> src/io/mod.rs:8:56
|
8 | .for_each(|v| if *v == 0.0 { f32::NAN } else { *v });
| ---------------------------------^^--
| | |
| | expected `()`, found `f32`
| expected this to be `()`
For more information about this error, try `rustc --explain E0308`.
有人可以指出正确的语法应该是什么,以将
Vec
替换为 0
吗?NaN
更典型的是:
.for_each(|v| if *v == 0.0 { *v = f32::NAN; });