How can the ref keyword be avoided when pattern matching in a function taking &self or &mut self?

后端 未结 1 1893
执笔经年
执笔经年 2020-11-28 15:55

The Rust book calls the ref keyword \"legacy\". As I want to follow the implicit advice to avoid ref, how can I do it in the following toy example? You can find

相关标签:
1条回答
  • 2020-11-28 16:49

    Since self is of type &mut Self, it is enough to match against itself, while omitting ref entirely. Either dereferencing it with *self or adding & to the match arm would cause an unwanted move.

    fn ref_mut(&mut self) -> &mut i32 {
        match self {
            OwnBox(i) => i,
        }
    }
    

    For newtypes such as this one however, &mut self.0 would have been enough.

    This is thanks to RFC 2005 — Match Ergonomics.

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