How to borrow the T from a RefCell as a reference?

前端 未结 1 1515
慢半拍i
慢半拍i 2021-01-21 00:16

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

相关标签:
1条回答
  • 2021-01-21 00:25

    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.

    0 讨论(0)
提交回复
热议问题