首页 > 解决方案 > 为什么这种模式匹配是必要的?

问题描述

我正在阅读这篇文章,就像不需要某些代码行一样。

例如在下面的例子中,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),
    }
}

标签: rust

解决方案


match需要访问内部值。ASocketAddr可以包含 aSocketAddrV4或 a SocketAddrV6,因此您需要处理这两种可能性。


推荐阅读