I'm trying to make a function that accepts an object that I can call iter()
on which will return an Iterator
that can be used with the print!
macro and display the object. I'm having issues on exactly how to define this. Most importantly, when I call this it can't move/destroy the object, so into_iter()
is out.
What I want to have the body like is this:
fn print_iterable<T>(iterable: &impl IntoIterator<Item = impl std::fmt::Debug>) -> () {
for cur in iterable.iter() {
print!("{:?}, ", cur);
}
}
This says that iterable
doesn't have a .iter()
method.
I can accept the idea that I may need to have the iterator as the direct argument so that my objects need to do .iter()
when calling it, instead of inside the function itself. I thought I needed std::fmt::Debug
for the {:?}
part, but that may not be right.
I'm basically trying to do something similar to the following C++ code:
template <class iterable> void iterPrint(const iterable& input, std::ostream& ostr = std::ref(std::cout))
{
ostr << "Contents: \"";
for (auto& cur : input)
{
ostr << " " << cur;
}
ostr << "\"\n";
}
Though honestly, I'm thinking of something closer to IEnumerable<T>
from C# as an equivalent.
I'm sure I'm missing something really basic here. I want to make a function that has an argument which is a reference to an object that implements a specific trait, and that trait has a bound which I need to specify as well. That it happens to be Iterator
and Debug
here isn't as important as knowing how to do this in general.