rust - 为什么这种模式匹配是必要的?
问题描述
我正在阅读这篇文章,就像不需要某些代码行一样。
例如在下面的例子中,match
真的有用吗?为什么需要它?看起来像重复的代码?也许编译器解决了这个问题并且它只是为了表现力而编写的?
#[stable(feature = "sockaddr_setters", since = "1.9.0")]
pub fn set_port(&mut self, new_port: u16) {
match *self {
SocketAddr::V4(ref mut a) => a.set_port(new_port),
SocketAddr::V6(ref mut a) => a.set_port(new_port),
}
}
解决方案
match
需要访问内部值。ASocketAddr
可以包含 aSocketAddrV4
或 a SocketAddrV6
,因此您需要处理这两种可能性。
推荐阅读
- java - 我的 JComboBox 中的错误 - 未选择所选选项
- c# - DurableTask nuget 包升级到 2.0.0 版本时找不到 Azure 持久功能编排客户端
- search - 如何将 & 搜索查询自动转换为 %26
- algorithm - 在线 DFS(人工智能)中的问题
- javascript - 如何在laravel中的分页期间保持复选框处于选中状态
- xamarin - 如何更改 Xamarin Shell 选项卡栏上图标的位置
- java - 如何在 Spring 数据中获取大小的嵌套对象
- javascript - 如何将点击事件添加到按钮数组及其位置?
- scheme - 球拍语言输出问题
- android - 从 Fragment 打开 Activity 后如何保持底部导航视图?