1

I would like indexing of my type to return a structure bounded with lifetime. The structure needs to contain a reference to the original type to be able to run some methods on it, like foo[index].bar().

When I try a simple approach

impl<'a> Index<usize> for Foo {
    type Output = FooIndex<'a>;

    fn index(&self, index: usize) -> &Self::Output {
        FooIndex {
            index,
            foo: &self,
        }
    }
}

I get the following error[E0207]: the lifetime parameter 'a is not constrained by the impl trait, self type, or predicates

Is there any way how to do it?

cripplejayb
  • 73
  • 1
  • 4
  • You can't return a borrowed `FooIndex<'a>` unless `Foo` contains a `FooIndex<'a>` to borrow. You can't create a `FooIndex` *inside* the `index` method and return it; that's a violation of the `Index` trait's interface. You'll be better served by just writing a `get` method. – trent Aug 20 '19 at 11:32
  • Also: https://doc.rust-lang.org/error-index.html#E0207 – Peter Varo Aug 20 '19 at 11:35
  • Also read [Is there any way to return a reference to a variable created in a function?](https://stackoverflow.com/questions/32682876/is-there-any-way-to-return-a-reference-to-a-variable-created-in-a-function) to better understand the error message. – trent Aug 20 '19 at 11:43

0 Answers0