IntoUrl vs. Url

The hyper crate offers two options for passing a url to a function: Using the trait IntoUrl or directly taking a Url. IntoUrl seems nicer in the first place, because it allows passing e.g. a String to function, but then the function does need to handle possible faults when converting IntoUrl to Url. Taking Url guarantees a valid url, but the caller is forced to convert his strings first.

So I was wondering which one to prefer. Or more generally speaking: What are the advantages and disadvantages of using IntoSomeStruct vs. SomeStruct in general? Is there some rule of thumb when to use which?

From my searching, It looks like IntoUrl was removed from hyper at some point. I gave a talk on the various naming conventions in Rust (see slide 12). From what I have seen, Into related traits normally does not require allocation and does not have an error variant. Instead, Into normally consumes a type and turns it into another type.

The advantage of using Into related traits is that it allows you to create a function that can accept multiple types. For example, you can create a function that accepts a String or a &str. This makes your code more ergonomic to the user, but has the downside of making your code a little more complex.

In the case of Url, you are right to identify that errors have to be handled. I think is odd to create a function that has to both fulfill its intended purpose while also dealing with the possible errors of converting a &String to a Url.

1 Like

Thanks for you're answer! Given that Into does not allocate nor fail, this concepts fully makes sense. It seems IntoUrl is still part of hyper, though (docs).