Is possible to implement a more general Index
trait for, say, Vec<T>
? I tried a few things but none of them worked:
// Attempt 1
trait Index2<I, R> {
fn index2(&self, index: &I) -> R;
}
// error: cannot infer an appropriate lifetime for autoref due to
// conflicting requirements
impl<'a, T> Index2<uint, &'a T> for Vec<T> {
fn index2(&self, index: &uint) -> &'a T {
self.index(index)
}
// The fully typed signature is
// fn index2(self: &'s Self, index: &'i I) -> &'a T
// The compiler doesn't know how 's and 'a are related
}
// Attempt 2
trait Index2<I, R> {
fn index2<'a>(&'a self, index: &I) -> R;
// This function declaration is equivalent to
// index2(&self, index: &I) -> R;
}
// error: method `index2` has an incompatible type for trait: expected
// concrete lifetime, but found bound lifetime parameter 'a
impl<'a, T> Index2<uint, &'a T> for Vec<T> {
fn index2<'a>(&'a self, index: &uint) -> &'a T {
unimplemented!()
}
}
// Attempt 3 (RFC #192 a.k.a lifetime bounds)
trait Index2<I, R: 'a> {
// R: 'a means that all the references contained in R must *outlive*
// 'a, this is the *opposite* of what's required for the Vec case
// For the Vec case, the lifetimes of the references in R must be equal
// or *shorter* than 'a
fn index2(&'a self, index: &I) -> R;
}
// Attempt 4 (Higher Kinder Type constructors?)
// R is a type constructor that takes a lifetime parameter as argument
trait Index2<I, R> {
// This may work, but we don't have HKT (yet?)
fn index2<'a>(&'a self, index: &I) -> R<'a>;
// With this method, I think index2 *can't* return a Copy type like int
}
// Attempt 5 (Vec auto-slicing)
// Is not possible to implement the Index2 trait for Vec
trait Index2<I, R> {
fn index2(&self, index: &I) -> R;
}
// Implement Index2 for a slice, and just use vec.as_slice().index2(i) everywhere
// If &Vec was automatically coerced to &'a [T], then we could also use vec.index2(i)
impl<'a, T> Index2<uint, &'a T> for &'a [T] {
fn index2(&self, &index: &uint) -> &'a T {
&self[index]
}
}
It can't be done? Or am I overlooking something simple?