Is it possible to create a wrapper around an &mut that acts like an &mut

前端 未结 1 424
甜味超标
甜味超标 2021-01-15 02:19

The following code fails to compile because MutRef is not Copy. It can not be made copy because &\'a mut i32 is not Copy. Is there any way give

1条回答
  •  长发绾君心
    2021-01-15 02:39

    No.

    The name for this feature is "implicit reborrowing" and it happens when you pass a &mut reference where the compiler expects a &mut reference of a possibly different lifetime. The compiler only implicitly reborrows when the actual type and the expected type are both &mut references. It does not work with generic arguments or structs that contain &mut references. There is no way in current Rust to make a custom type that can be implicitly reborrowed.

    However, you can implement your own method to explicitly reborrow:

    impl<'a> MutRef<'a> {
        // equivalent to fn reborrow(&mut self) -> MutRef<'_>
        fn reborrow<'b>(&'b mut self) -> MutRef<'b> {
            MutRef {v: self.v}
        }
    }
    
    fn wrapper() {
        let mut s: i32 = 9;
        let mut q = MutRef{ v: &mut s };
        wrapper_use(q.reborrow());  // does not move q
        wrapper_use(q);             // moves q
    }
    

    See also

    • Why is the mutable reference not moved here?
    • Type inference and borrowing vs ownership transfer

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