How it works...

In this recipe, we use the parse method of the url crate to validate and parse a &str from the data into a Url struct. The input string will be transformed into Result<Url, ParseError> on the method's return value.

We create a variable named s and assign it to the URL that we want to parse; the value is sent to the method with Url::parse(s). Once the URL has been parsed, it can be used with all methods on the URL type. Finally we print the path part of the parsed variable that stores the return value of the parse method.

The URL in this code parses successfully, but swapping it out for a malformed URL will print a message containing an explanation of what went wrong.

The error-chain crate is a library for consistent and reliable error handling that makes it easier to take full advantage of Rust's powerful error-handling features, without the overhead of maintaining boilerplate error types and conversions. It implements a strategy for defining your own error types, as well as conversions from others' error types.

The basic pattern we use here has a function named run() that produces a Result that acts like a real main function. We use the error-chain crate to make ? work within run. This is using the error_chain! macro from error-chain to define a custom Error and Result type, along with automatic conversions from the crate error types. The automatic conversions make the ? operator work. The quick_main! macro generates the actual main function and prints out the error if it occurs during the course of execution.

We return Ok(()) to the quick_run! macro to ensure that the program executed successfully without any errors.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.200.71