3 ms·
> Given how general Range is, how does it even implement a len() which has the behavior in the article? len() is hidden in ExactSizeIterator, which is implemen
by MaulingMonkey 6y ago
> Given how general Range is, how does it even implement a len() which has the behavior in the article?
len() is hidden in ExactSizeIterator, which is implemented for a bunch of Range specializations: https://doc.rust-lang.org/std/ops/struct.Range.html#impl-ExactSizeIterator https://doc.rust-lang.org/std/ops/struct.Range.html#impl-Exa...
Expanding the docs node and following the [src] link for len, we can see it's using ExactSizeIterator's default implementation, which invokes size_hint: https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#99-107 https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs...
ExactSizeIterator only requires Iterator: https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs.html#71 https://doc.rust-lang.org/src/core/iter/traits/exact_size.rs...
And sure enough, that's where size_hint is implemented in Range: https://doc.rust-lang.org/std/ops/struct.Range.html#impl-Iterator https://doc.rust-lang.org/std/ops/struct.Range.html#impl-Ite... -> https://doc.rust-lang.org/src/core/iter/range.rs.html#515-522 https://doc.rust-lang.org/src/core/iter/range.rs.html#515-52...
Which in turn relies on steps_between, which is implemented via macro for various integer types:
https://doc.rust-lang.org/src/core/iter/range.rs.html#240-247 https://doc.rust-lang.org/src/core/iter/range.rs.html#240-24...
https://doc.rust-lang.org/src/core/iter/range.rs.html#360-372 https://doc.rust-lang.org/src/core/iter/range.rs.html#360-37...
https://doc.rust-lang.org/src/core/iter/range.rs.html#388-404 https://doc.rust-lang.org/src/core/iter/range.rs.html#388-40...