Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset all array elements?

Tags:

arrays

rust

This is the shortest I came up with, after extensive googling and studying the sources:

let mut buf = [0u8; 200];
for elem in buf.iter_mut() {
    *elem = 0;
}

Is there really no way to make this a one-liner, like buf.set_all(0)?

like image 510
Michael Böckling Avatar asked Jul 17 '26 15:07

Michael Böckling


2 Answers

Is there really no way to make this a one-liner, like buf.set_all(0)?

Sure you can make it a one-liner...

for elem in buf.iter_mut() { *elem = 0; }

Okay, okay... if you do this a lot, you can define an extension trait that provides a set_all method.

trait SetAll {
    type Elem;
    fn set_all(&mut self, value: Self::Elem);
}

impl<T> SetAll for [T] where T: Clone {
    type Elem = T;
    fn set_all(&mut self, value: T) {
        for e in self {
            *e = value.clone();
        }
    }
}

But in terms of just using what's in the standard library, there's for_each (as noted by Sven Marnach):

buf.iter_mut().for_each(|x| *x = 0)
like image 97
DK. Avatar answered Jul 20 '26 08:07

DK.


Update: the slice::fill method is now stable since 1.50.

like image 38
Michael Böckling Avatar answered Jul 20 '26 09:07

Michael Böckling