Z
Z
ziplane2019-08-04 19:07:49
Rust
ziplane, 2019-08-04 19:07:49

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)
    }

now I want to make a function where one can square regardless of the type
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)
    }
}

and it doesn't work. Can you explain or give a link what is wrong.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Lesnikov, 2019-08-14
@ziplane

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);
}

playground

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question