3 ms·
But even then the point still stands: you wouldn't want a non-custom debug representation of the iterator precisely because of the cost. You could create a new-
by estebank 4y ago
But even then the point still stands: you wouldn't want a non-custom debug representation of the iterator precisely because of the cost. You could create a new-type that wraps your iterator and implements a custom `Debug` impl with the contents you desire. Here the issue at play seems to be a disagreement on what is more useful in a Default implementation: a preview of the results of the iteration or a representation of the type structure. I believe that which of the two is more useful depends entirely on what you're using the Debug info for (with the caveat that going from the later to the former in your head is possible, but the other way around isn't).
- Arnavion 4y agoYou can't preview an arbitrary Iterator anyway because iterating is destructive. The elements you iterated will be gone forever. Besides, the typesystem won't let you do it anyway, since collect() requires either `Self` or `&mut Self`, and `fmt` only receives `&Self`. So at best you could only do this with Clone'able Iterators, but even then it might not be ideal for formatting to create "wasteful" clones. So maybe you'd only do it for individual Iterator types like Range or std::slice::Iter for which cloning is cheap. But even .map()ping such a trivially-Cloneable Iterator would yield a non-Cloneable or non-trivially-Cloneable Iterator, so at that point you have to wonder if it's worth making a small subset of Iterators have these "useful" Debug impls.
- spoiler 4y agoBut even in Cpp, you need to eventually iterate over the underlying iterator to get the results of the map. So, if you want to debug print it, you still need to iterate over it regardless. Regarding the mutability and collect issues you raised, I think I just explained poorly. What I meant is that the author could've done something like this https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=e58b99ff86a5f26e98c023ed39f596b8 https://play.rust-lang.org/?version=stable&mode=debug&editio... However, debug printing "on the fly" (without collection first) would definitely be more involved with interior mutability and require a wrapper type, for the reasons you outlined, but not impossible.
- Arnavion 4y agoYour playground is what the article author did, except they used `itertools::Itertools::format` so that the entire collection or formatted string doesn't need to be built up-front but can instead be fed to the `std::fmt::Formatter` element-by-element.
- spoiler 4y agoAh, I understand that part, but I assumed they were looking for the most ergonomic/succinct and idiomatic approach (ie not needing to reach for a crate). But it doesn't have the same performance characteristics as using itertools (which is better here)