How to Parse URLs in Rust

Parse URLs in Rust by using the url crate's parse method to convert strings into structured Url objects.

Use the parse() method on a string slice to convert a URL string into a Url struct, handling errors with expect or match.

use url::Url;

fn main() {
    let url_str = "https://example.com/path?query=1";
    let url: Url = url_str.parse().expect("Invalid URL");
    println!("Scheme: {}, Host: {}, Path: {}", url.scheme(), url.host_str().unwrap(), url.path());
}

Add url = "2.5" to your Cargo.toml dependencies to use this crate.