User friendly IpAddr


#1

Hello,
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)
where
    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 = "127.0.0.2".parse().unwrap();
with_ip(ip);

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.


#2

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


#3

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