Constrain parent trait to reference

I want to define a trait Container such that every implementor of this trait also needs to implement IntoIterator, with the caveat that the iteration ALWAYS only borrows the instance. If I understand correctly, I can implement IntoIterator using a pattern like this:

impl<'a> IntoIterator for &'a ContainerImpl

However, how can I specify that this needs to be implemented if a type implements Container, e.g.:

trait Container: &IntoIter ???

Answers


You can add a where clause to traits, too (playground):

trait IterBorrow where for<'a> &'a Self: IntoIterator {}
impl IterBorrow for [i32] {} // legal
// impl IterBorrow for i32 {} // Illegal

However, it seems you currently need to reiterate this bound whenever you actually want to iterate, i.e., this function does not compile without the where clause:

fn foo<T: IterBorrow>(x: T) where for<'a> &'a T: IntoIterator {
    for _ in &x {}
    for _ in &x {}
}

Need Your Help

SQL: Selecting current month last year

sql sql-server-2008 date

I currently select data from the current month LAST year. This works fine with

Getting the current value of a select tag

javascript jquery dom select

When I try to get the selected option in a select tag in the current DOM