by masklinn · 10y ago · 0 comments
Returning an Option. That's what Elm does:
head : List a -> Maybe a
get : Int -> Array a -> Maybe a
It tends to drive people towards not indexing collection (which is often good).Perhaps we should have a clippy lint for this.
I have seen quite a bit of regular `[]` indexing, however it's almost always in very obvious situations, and most of the places where you might index in C/++ (iteration, or with a bounds check) I've seen people using iterators or the monadic way.
But yeah, it's not that unidiomatic. It's still used a lot, just not to the extent it's used elsewhere.
(For example, we have thrice as much indexing in our DOM binding generation python code (`components/script/dom/bindings/codegen`) in Servo than we do in all of the non-test rust files (`components/`) in the main repo combined)
There may be ways to lint in case of an `if x.len()... x[...]` though. That should be done monadically; given that panics aren't supposed to be caught in most situations, we should minimize the number of ways programmer error can lead to a panic.
Looking through servo's code a lot of the cases are where we use fixed-length arrays, or when dealing with graphicsy buffers. One use case which needs indexing is when we use an index as an "id". No easy way to fix that without introducing Rc or something.