【发布时间】:2017-08-29 13:24:30
【问题描述】:
我正在尝试在 Vec 内使用 Vec<f64> 制作的矩阵上进行循环,然后一一更改其元素。
我似乎无法让它工作;我仍然对语法感到困惑......
extern crate rand;
use std::ptr;
use std::mem;
use rand::Rng;
fn main() {
let mut rng = rand::thread_rng();
let mut v: Vec<Vec<f64>> = Vec::new();
v.push(vec![0f64; 35]);
v.push(vec![0f64; 35]);
v.push(vec![0f64; 35]);
v.push(vec![0f64; 35]);
let len = v.len();
for &el in &v {
for q in &mut el {
q = rng.gen::<f64>();
println!("{}", q);
}
println!("{:?}", el);
}
println!("float: {}", rng.gen::<f64>());
//println!("vec: {:?}, len: {}",v,len);
}
编译器这样说:
error[E0308]: mismatched types
--> src/main.rs:19:17
|
19 | q = rng.gen::<f64>();
| ^^^^^^^^^^^^^^^^ expected &mut f64, found f64
|
= note: expected type `&mut f64`
found type `f64`
= help: try with `&mut rng.gen::<f64>()`
我尝试遵循编译器提示,mut & 和 .iter() 或 .iter_mut() 的各种组合,但它们都不起作用。在一些挫折之后,我注意到我对解决方案的搜索已经变成了蒙特卡洛算法。
【问题讨论】:
标签: for-loop rust mutable borrowing