User friendly IpAddr

I am trying to make a simple API a bit more user friendly. I have a function that takes an IpAddr and I have refactored it to use the magic Into trait:

fn with_ip<I>(ip: I)
    I: Into<IpAddr>,
    assert_ne!(ip.into(), Ipv4Addr::new(127, 0, 0, 1));

This works well for some types of parameters:

with_ip([127, 0, 0, 2]);

But it is a bit clunky when I want to use a &str:

let ip: IpAddr = "".parse().unwrap();

I notice that IpAddr does implement the FromStr trait. Is there any way to get the best of both worlds and be able to pass a &str and the Into types?

Link to playground

Thanks in advance for your help.

Not straightforwardly, since the conversion from &str (and FromStr in general) can fail, while Into can't.

1 Like

Have a look at the ToSocketAddr trait instead of "Into". (Sorry for no link, I'm on the go)