铁锈书称为ref关键词“遗产” https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#legacy-patterns-ref-and-ref-mut。因为我想遵循隐含的建议来避免ref
,在下面的玩具示例中我该怎么做?您也可以在.
struct OwnBox(i32);
impl OwnBox {
fn ref_mut(&mut self) -> &mut i32 {
match *self {
OwnBox(ref mut i) => i,
}
// This doesn't work. -- Even not, if the signature of the signature of the function is
// adapted to take an explcit lifetime 'a and use it here like `&'a mut i`.
// match *self {
// OwnBox(mut i) => &mut i,
// }
// This doesn't work
// match self {
// &mut OwnBox(mut i) => &mut i,
// }
}
}
Since self
属于类型&mut Self
,与自身匹配就足够了,同时省略ref
完全。要么取消引用它*self
或添加&
到匹配臂上会导致不必要的移动。
fn ref_mut(&mut self) -> &mut i32 {
match self {
OwnBox(i) => i,
}
}
然而对于像这样的新类型来说,&mut self.0
就足够了。
这要归功于RFC 2005 — 匹配人体工程学 https://rust-lang.github.io/rfcs/2005-match-ergonomics.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)