Parsing a Url from a String

Hi. New to rust and am trying to parse a String to a Url.
I see this function in the docs:

pub fn parse(input: &str) -> Result<Url, ParseError>

But I can’t seem to find an equivalent function for parsing a String.
Presumably, I wouldn’t be able to parse arbitrary, user supplied strings with &strs.
Is there something I’m missing?

&str can point to part or all of any string in memory, whether it’s in static memory (like a string literal) or in heap memory owned by a String, or wherever.

You can parse a Url from a String by passing a reference to it:

let s = String::from("foo");
let u = Url::parse(&s);

This works because a String is a type of pointer to a str slice. You can read more about this in the book chapters on string slices and deref coercions.

2 Likes

Thanks. The sad part is I just read about that yesterday :man_facepalming:

1 Like

You can pass the string as an argument, but put a & on the front, &String will coerce to &str in this situation.

1 Like