3 ms·
I'm really confused... Is all of this just the equivalent of `Enumerable.Empty<T>` or `yield return` in C#?
by ryanjshaw 2y ago
I'm really confused... Is all of this just the equivalent of `Enumerable.Empty<T>` or `yield return` in C#?
- sk11001 2y agoSo you do agree that other languages achieve the same thing with much less complexity?
- tcfhgj 2y agoNot exactly the same thing though
- MereInterest 2y agoNot quite, because the user of those would need to perform dynamic dispatch in order to iterate over the result. In the article, the returned iterator has a type that is known to the compiler, and so the caller’s code can be optimized much more effectively.
- Measter 2y agoI'll ignore the option of returning a Vec or Option, as the article already went over why these options were rejected, and concentrate on the later options. Firstly the `std::iter::empty()` attempt: The issue they had here came down to the signature of the function. What they wanted to do was return an `impl Iterator<Item=&N>`. This means that the function isn't naming the specific type it returns[1], only stating that it's an Iterator that gives some `&N`s. However, the return type of this function is still one, specific type. You cannot return two different types that are both iterators. That's why this one failed. Boxing: Instead, we can return a `Box<dyn Iterator<Item=&N>>`. This is roughly equivalent to a function in C# returning an `IEnumerabale<N>`, in that the actual type is hidden, and the work is done doing dynamic dispatch. This allows you to return different kinds of iterators, because the specific type is hidden away inside the Box. The downside here is that you're doing a heap allocation. OptionIterator: This one is actually basically just the first Option case from earlier but wrapped up in a nicer-to-use interface for the user because it implements Iterator in a way that transparently handles the Option. [1] Additionally, it's not even possible to name the type of the iterator here due to the filter closure being unnamable.