Printing Enum values

I’ve searched for this, but only found ways to display the actual Enum “type” itself rather than the “stored value.”

See the following code for what I’m trying to do:

enum IpAddr {
    V4(String),
    V6(String),
}
    
fn main()
{
    let home = IpAddr::V4(String::from("127.0.0.1"));
    let loopback = IpAddr::V6(String::from("::1"));
    print_ip(home);
}

fn print_ip(ip: Option<IpAddr>)
{
    match ip
    {
        Some(val) => println!("{}", val),
        None => println!("No value to print!")
    }
}

This does not compile whether I specify the ip parameter as a IpAddr directly, or an Option as shown here. I’m looking for the simplest way to write out the value stored in the enum, which in this case are Strings. Is there a way to access the value directly or must I use a match? Thank you.

1 Like

You could implement std::fmt::Display for IpAddr or match the enum in your print function, see print_ip2 snippet.

impl std::fmt::Display for IpAddr {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            IpAddr::V4(v) => v.fmt(f),
            IpAddr::V6(v) => v.fmt(f),
        }
    }
}
fn print_ip2(ip: Option<IpAddr>)
{
    match ip
    {
        Some(IpAddr::V4(val)) => println!("{}", val),
        Some(IpAddr::V6(val)) => println!("{}", val),
        None => println!("No value to print!")
    }
}

full example

2 Likes

As the type in both variants is the same (a String), we only need one match arm, reducing code duplication:

impl std::fmt::Display for IpAddr {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            // v is a String in both cases
            IpAddr::V4(v) | IpAddr::V6(v) => v.fmt(f),
        }
    }
}
1 Like