AggelosT
AggelosT

Reputation: 168

Multiply all elements of an array by a number? (Rust)

I have an array of four elements:

let mut arr: [u8; 4] = [0xff, 0x4d, 0xff, 0xff];

I want to slightly change the final values (Except the last one) with a random float. For now, let's say this random float isn't random, it's the number 0.92.

I could do this:

let random_float = 0.92;
arr[0] *= random_float;
arr[1] *= random_float;
arr[2] *= random_float;

But it's slow to write, plus it's basically the same line of code three times with the index value changing. So is there a better way to write this?

Upvotes: 1

Views: 3015

Answers (1)

isaactfa
isaactfa

Reputation: 6657

You couldn't actually write

arr[0] *= random_float;
arr[1] *= random_float;
arr[2] *= random_float;

as arr[0] has type u8 and random_float has type f64. Rust won't let you multiply those two types because it's not entirely clear what the desired result is. You need to cast the numbers between each others' types to work with them:

arr[0] = (arr[0] as f64 * random_float) as u8;

But that is, as you pointed out, quite tedious.

You can use a loop instead:

for b in arr[0..3].iter_mut() {
    *b = (*b as f64 * random_float) as u8;
}

Or the equivalent one-liner with for_each:

arr[0..3].iter_mut().for_each(|b| *b = (*b as f64 * random_float) as u8);

Upvotes: 3

Related Questions