Sometimes I have a struct
containing a value which is wrapped in a RefCell
, and I want to borrow the value, but I don\'t want to make the signature of
This is exactly the purpose of impl Trait
, which has been available in stable Rust since version 1.26.
use std::ops::Deref;
impl<T> Outer<T> {
fn get_inner_ref<'a>(&'a self) -> impl Deref<Target = T> + 'a {
self.inner.borrow()
}
}
The Rust compiler knows that the actual implementation is Ref<T>
but lets you avoid having to write it explicitly, and callers of this function can only use functionality provided by the Deref
trait.
As long as the actual value that you return is of a type that implements Deref<Target = T>
, you are free to change that implementation later without breaking any code that uses it. For example, you could return &T
or one of several other reference types, including your own custom type, as in the other linked question.