3 ms·
Idiomatically you should be using iterators or monadic indexing (i.e. the methods which return an Option). Regular indexing is exposed for convenience, but I do
by Manishearth 11y ago
Idiomatically you should be using iterators or monadic indexing (i.e. the methods which return an Option). Regular indexing is exposed for convenience, but I don't think it should be used as often.
Perhaps we should have a clippy lint for this.
- kzrdude 11y agoLol, you must live in a different world, lots of code is using regular bounds checked indexing and it is completely idiomatic. So idiomatic in fact that there is no nonpanicking slicing method for slices or strings, for example.
- Manishearth 11y agoYou don't need one, since you can use `.chars().nth()` (indexing a string needs you to iterate over it anyway, because utf8). Though I do feel that having a direct get() API would be nice 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)
- Gankro 11y agoDon't. This would be a terrible lint. It's perfectly reasonable to expect an index to be in bounds for various reasons.
- mcguire 11y agoDependent typing, dude. It's the way of the future.
- Manishearth 11y agoIt could be a pedantic lint (off by default). 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.