▲ 7 r/learnrust
Interator Initialisation Question
So, the idea behind Iterators is that they are Lazy and don't do any work until called. But at the same time Rust likes to have fully initialised objects.
So, if my initialisation takes considerable time (think opening a file, connecting to a network, etc) should I do that in the constructor of the iterator so that it is fully initialised, or at the first step in the iteration so that the Iterator is lazy?
I waffle backwards and forwards on this myself and would love to know what the consensus is.
e.g. Something like
struct MyIterable {
network:OpenSocket,
}
impl MyIterable {
fn new(args:Args) -> Self {
// might take a long time
Self { network: open_network(args) }
}
}
impl Iterator for MyIterable {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
network.get_next()
}
}
vs something like
struct MyLazyIterable {
args:Args,
network:Option<OpenSocket>,
}
impl MyLazyIterable {
fn new(args:Args) -> Self {
Self { args, network:None }
}
}
impl Iterator for MyLazyIterable {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
if let Some(network) = self.network.as_mut() {
network.network.get_next()
} else {
// might take a long time
let network = open_network(self.args);
let item = network.get_next();
self.network = Some(network);
item
}
}
}
u/dgkimpton — 4 days ago