【问题标题】:Rust Enums, Match & Destructuring - hep me understandRust 枚举、匹配和解构 - 让我明白
【发布时间】:2022-11-01 22:19:54
【问题描述】:

我正在学习 Rust。我在 JavaScript 和 Python 方面有一些编程经验,并且曾经在 Haskell 上过得很好。

我正在学习枚举,但发现很难使用它们。这就是我正在做的事情:

fn main(){
    enum IpAddr {
        V4(u8, u8, u8, u8),
        V6(u16, u16, u16, u16, u16, u16, u16, u16),
    }
    impl IpAddr {
        fn last_octet (&self) -> &u16 {
            match &self {
                IpAddr::V4(_, _, _, d) => d as &u16,
                IpAddr::V6(_, _, _, _, _, _, _, h) => h,
            }
        }
    }
    let localhost4 = IpAddr::V4(127, 0, 0, 1);
    let localhost6 = IpAddr::V6(0, 0, 0, 0, 0, 0, 0, 1);        
    println!("{}", localhost4.last_octet());
    println!("{}", localhost6.last_octet());
}

所以,我想分别对 IPv4 和 IPv6 使用 u8 和 u16 来利用类型系统。

我意识到我的 last_octet 方法只能返回一种有点限制的类型,所以显而易见的方法似乎将我的 IPv4 八位字节转换为 u16,但我无法找到一种方法来做到这一点。

关于我所做的任何建议或改进?

我在上面尝试了我的主要功能,但从 u8 到 u16 的转换失败了。

如果我尝试同样的简单

let u8: u8 = 7;
let u16: u16 = u8 as u16;

没有问题。所以,我不了解枚举或它们的方法。

【问题讨论】:

    标签: rust enums


    【解决方案1】:

    问题是您试图返回对u16 的引用,并且不能在对不同类型的引用之间进行简单的转换。好消息是几乎没有充分的理由返回对整数的引用而不仅仅是一个整数。 Rust 中的所有整数类型都是 Copy,即它们不会被移动,它们只是被一点一点地复制,因为它便宜得多,而且它们不拥有任何可能在此过程中产生别名的数据。所以你可以只返回一个u16 而不是&u16 并上传你的u8

    impl IpAddr {
        fn last_octet (&self) -> u16 {
            match &self {
                // note the dereferencing operator `*` here to turn a `&u8` into a `u8`
                // before casting it to a `u16`:
                IpAddr::V4(_, _, _, d) => *d as u16,
                // here we just need to dereference:
                IpAddr::V6(_, _, _, _, _, _, _, h) => *h,
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-03
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-04
      相关资源
      最近更新 更多