Answer the question
In order to leave comments, you need to log in
Generalizations. How to square elements in a vector?
Good day!
I want to square the elements in a vector for this
let sim:Vec<f64> = vec![0.10,20.60,17.7];
//создаю цикл и он работает
for i in sim.iter_mut(){
*i = (*i) + (*i)
}
fn main() {
let mut sim:Vec<f64> = vec![0.10, 20.60, 17.7];
quadrat(sim);
}
fn quadrat<T:AddAssign+Add> (mut input:Vec<T>)
{
//input.iter().map(|n|n*n);
for i in input.iter_mut() {
*i = (*i) + (*i)
}
}
Answer the question
In order to leave comments, you need to log in
If you want to modify an external array, then it must be received by `&mut` reference. `mut input:Vec` will simply move the argument, `mut` will make it mutable only within the function (similar to normal `let mut` declarations).
If you want to assign the result of a generalized multiplication to a variable of type T, then you must explicitly require the Output multiplication trait to have the appropriate type: `Mul`.
Also, if you want to use dereferences (`*`), you must require the `Copy` trait.
use std::ops::Mul;
fn square_elements<T: Mul<Output=T> + Copy>(data: &mut [T]) {
for i in data.iter_mut() {
*i = *i * *i;
}
}
fn main() {
let mut v: Vec<f64> = vec![0.10, 20.60, 17.7];
println!("before: {:?}", v);
square_elements(&mut v);
println!("after: {:?}", v);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question