3 ms·
So in Rust you must specify the length of an array? How do you implement map, fold, etc., that work on an entire collection regardless of length? Is that a diff
by maxfurman 6y ago
So in Rust you must specify the length of an array? How do you implement map, fold, etc., that work on an entire collection regardless of length? Is that a different API in Rust?
- steveklabnik 6y ago> So in Rust you must specify the length of an array? Correct. > How do you implement map, fold, etc., that work on an entire collection regardless of length? So, while arrays exist, there are also things like slices and vectors, which have a runtime length, rather than an array's compile-time length. So that's one bit of it. But the other part is that these are implemented on iterators, rather than on the type directly, so usually what happens is "turn that into an iterator, then do map/fold/filter/whatever on the iterator. It is easy to convert the compile-time length array to a run-time length iterator, so it ends up being a uniform interface.
- maxfurman 6y agoThat makes sense. Thanks!
- jadbox 6y agoSo would const generics for arrays make map/fold somewhat faster because there would be no need to create an iterator?
- steveklabnik 6y agoYou would still need to create an iterator, because there are three different ways to iterate, and you have to pick which one you want. However, often times it entirely compiles away to nothing. What this may help with is bounds checks; it is possible for this to make it easier to remove/hoist bounds checks in some circumstances. In my understanding.
- justadudeama 6y agoYes, there is `Vec` that allows arbitrary length arrays, and iterators implement those other functions
- deleted 6y ago[deleted]
- KuiN 6y agoMap, fold etc. are implemented on the `Iterator` trait. [1,2,3].iter().map(|x| x + 1) https://doc.rust-lang.org/std/iter/trait.Iterator.html https://doc.rust-lang.org/std/iter/trait.Iterator.html