在生锈中实例化枚举时出错

时间:2015-04-17 23:24:33

标签: rust

我正在尝试这样做:

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

// A network
pub enum IpNetwork {
    V4(Ipv4Network),
    V6(Ipv6Network),
}

pub struct Ipv4Network {
    addr: Ipv4Addr,
    prefix: u8,
}

pub struct Ipv6Network {
    addr: Ipv6Addr,
    prefix: u8,
}

impl Ipv4Network {
    fn new(addr: Ipv4Addr, prefix: u8) -> Ipv4Network {
        Ipv4Network { addr:addr, prefix:prefix }
    }
}

impl Ipv6Network {
    fn new(addr: Ipv6Addr, prefix: u8) -> Ipv6Network {
        Ipv6Network { addr:addr, prefix:prefix }
    }
}

impl IpNetwork {
    pub fn new(ip: IpAddr, prefix: u8) -> IpNetwork {
        match ip {
            IpAddr::V4(a) => IpNetwork::V4(a, prefix),
            IpAddr::V6(a) => IpNetwork::V6(a, prefix),
        }
    }
}

fn main() {
    let ip = Ipv4Addr::new(77, 88, 21, 11);
    let cidr = IpNetwork::new(ip, 24);
}

这给了我:

src/lib.rs:34:30: 34:54 error: this function takes 1 parameter but 2 parameters were supplied [E0061]
src/lib.rs:34             IpAddr::V4(a) => IpNetwork::V4(a, prefix),
                                           ^~~~~~~~~~~~~~~~~~~~~~~~
src/lib.rs:35:30: 35:54 error: this function takes 1 parameter but 2 parameters were supplied [E0061]
src/lib.rs:35             IpAddr::V6(a) => IpNetwork::V6(a, prefix),
                                           ^~~~~~~~~~~~~~~~~~~~~~~~
src/lib.rs:42:31: 42:33 error: mismatched types:
 expected `std::net::ip::IpAddr`,
    found `std::net::ip::Ipv4Addr`
(expected enum `std::net::ip::IpAddr`,
    found struct `std::net::ip::Ipv4Addr`) [E0308]
src/lib.rs:42     let cidr = IpNetwork::new(ip, 24);
                                            ^~
error: aborting due to 3 previous errors

为什么rust认为构造函数需要一个参数?

2 个答案:

答案 0 :(得分:2)

变体的格式为V4(Ipv4Network),因此您应该传递Ipv4Network,例如Ipv4Network::new(a, prefix)

IpAddr::V4(a) => IpNetwork::V4(Ipv4Network::new(a, prefix)),

答案 1 :(得分:1)

您的代码中有两个错误:

第一个错误就是你,例如通过传递一个地址元组和一个前缀来构造IpNetwork::V4。如果你看看你如何定义IpNetwork

// A network
pub enum IpNetwork {
   V4(Ipv4Network),
   V6(Ipv6Network),
}

您需要向IpNetwork::V4提供struct Ipv4Network,而不仅仅是(a, prefix)的元组。同样适用于IpNetwork::V6。通过这些调整,您的匹配括号变为:

pub fn new(ip: IpAddr, prefix: u8) -> IpNetwork {
    match ip {
        IpAddr::V4(a) => IpNetwork::V4(Ipv4Network::new(a, prefix)),
        IpAddr::V6(a) => IpNetwork::V6(Ipv6Network::new(a, prefix)),
    }
}

第二个错误在main方法中。您正在构建Ipv4Addr并尝试将其作为参数传递给IpNetwork。虽然IpNetwork仅接受IpAddr。所以你会错过这一部分:

let addr = IpAddr::V4(ip);
let cidr = IpNetwork::new(addr, 24);

以下是针对不稳定参数失败的解决方案的playpen link

要使此代码段起作用,您需要创建一个包,并为其添加#![feature(ip_addr)]以通过编译器检查。 IpAddr和变种显然正在重新制作。