Suppose I have a handler trait of sorts that handles types who implement some trait, like this:
trait Handler<T: Foo> {
fn handle<'a>(&self, what: &'a T) -> Result<&'a T>;
}
(Where Result
is some arbitrary type referencing the input.)
This is perferctly ok and works well.
However, I then figured that besides handling things by reference I'd also like to handle stuff like struct Something<'a>(&'a str)
, which is conceptually similar, but suddenly I don't know how to express this in the trait definition. I can't do this:
trait Handler<T: Foo> {
fn handle(&self, what: T) -> Result<T>;
}
impl<'a> Handler<Something<'a>> for MyHandler { ... }
... because then the whole trait object is subject to the lifetime, ie. cannot outlive the types passed into the handle()
method. But I also can't move the generic type from the trait to the method, because that breaks object safety.
Edit: what
also can't be &dyn Foo
because the handle()
method needs the specific type.
Is it at all possible to solve this in current Rust? What are my options here?
Thanks!