I have the following Rust function
fn query_list_or_empty<'a, P, R>(
conn: &'a mut SimpleConnection,
sql: &'a str,
params: P,
) -> Peekable<Box<dyn Iterator<Item = Result<R, FbError>> + 'a>>
where
P: rsfbclient::IntoParams,
R: FromRow + 'static,
{
match conn.query_iter(sql, params) {
Ok(iter) => iter.peekable(),
Err(e) => {
error!("Failed to execute query: {}", e);
Box::new(std::iter::empty::<Result<R, FbError>>()).peekable()
}
}
}
In case of an error I just want to log the error and return an empty peekable iterator, however I can not find how to initialize an empty list of the correct type - Peekable<Box<dyn Iterator<Item = Result<R, FbError>> + 'a>>
I found how to return an empty NONE PEEKABLE iterator like this:
fn query_list_or_empty<'a, P, R>(
conn: &'a mut SimpleConnection,
sql: &'a str,
params: P,
) -> Box<dyn Iterator<Item = Result<R, FbError>> + 'a>
where
P: rsfbclient::IntoParams,
R: FromRow + 'static,
{
match conn.query_iter(sql, params) {
Ok(iter) => iter,
Err(e) => {
error!("Failed to execute query: {}", e);
Box::new(std::iter::empty::<Result<R, FbError>>())
}
}
}
It works fine and I can call it and add the "packability" later like this:
let mut rows_iter = query_list_or_empty(
&mut conn,
&config.select_candidates,
(&config.step_id, &config.block_period),
)
.peekable(); // <- make it peekeable
Although it is a solution, I do want to make it work - this is challenging Rust I want to master....