[英]Using iter().map on a VecDeque of struct containing tuples
I am new in Rust.我是 Rust 的新手。 I have the following problem:
我有以下问题:
pub struct Events {
pub ts: u64,
pub temperature_multiplier: (f64,f64), // (temperature,multiplier)
}
I have a VecDeque of this struct我有这个结构的 VecDeque
elements_vec: VecDeque<Events>
I would like to be able to go through all the elements of VecDeque and compute the the sum of (temperature * multiplier).我希望能够通过 VecDeque 的所有元素 go 并计算(温度*乘数)的总和。
What I have tried:我试过的:
elements_vec.iter().map(|(_, (t,m))| t * m ).sum()
It returns an error saying "expected Struct Events".它返回一个错误,说“预期的结构事件”。
Events
is not a tuple but a struct. Events
不是一个元组,而是一个结构。 You need to go through Destructuring Structs section in rust book .您需要通过rust book 中的 Destructuring Structs 部分来 go 。
elements_vec.iter().map(|Events { temperature_multiplier: (t, m), .. }| t * m).sum::<f64>()
This is how I understood your question:我是这样理解你的问题的:
let mut elements_vec: VecDeque<Events> = VecDeque::with_capacity(10);
elements_vec.push_back(Events { ts: 0x0002, temperature_multiplier: (20.0, 2.0) });
elements_vec.push_back(Events { ts: 0x0003, temperature_multiplier: (30.0, 3.0) });
elements_vec.push_front(Events { ts: 0x0001, temperature_multiplier: (10.0, 1.0) });
println!("{:?}", &elements_vec);
let s : f64 = elements_vec.iter().map(|evnt| evnt.temperature_multiplier.0 * evnt.temperature_multiplier.1 ).sum();
println!("s: {}", s); // s: 140
The answer is in the compiler's message: map()
needs struct Events
, which we give it as map(|evnt| /* and use it here */)
.答案在编译器的消息中:
map()
需要struct Events
,我们将其作为map(|evnt| /* and use it here */)
。 And it works!它有效!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.