please summarize this part of a chapter of a book on rust programming, outlining each…
- User
please summarize this part of a chapter of a book on rust programming, outlining each section with explanations: “ Rust comes equipped with a large set of tools that makes it easy to organize, struc- ture, test, and comment it. The ecosystem values good documentation style, which is the reason Rust has a built-in commenting system that generates code documen- tation on the fly, and even tests the code in your comments so your documentation is never out-of-date. A widely supported linter called Clippy is the de facto standard in the Rust world. It comes with many preset rules and helps point out best practices or missing implementations. In addition, Rust’s package manager Cargo helps autoformat your code based on predefined rules. In the preceding chapter, we built out API routes for our Q&A applications, extracted information out of URL parameters, and most importantly, added our own structures and error implementations and handling. We added all this into the main.rs file, which grew with every route handler we added. Clearly, this file does too much. Even for a large application, the main.rs file should just connect all the pieces and start the server instead of owning any real implementa- tion logic. In addition, we added a lot of custom code that could use some explanations. We could use Rust’s built-in capabilities of splitting code and documenting it. We start off this chapter by looking at the module system to see how to split your code and how to make it public or private. Later, we’ll add comments, write code exam- ples in doc comments, and lint and format our code. 5.1 :Modularizing your code So far, we put every line of code in the main.rs file of our project. This can work well for a small mock server you want to run and maintain in your service architecture, because it is easier to maintain, and not a lot will change after the initial creation. A larger and more actively maintained project, however, is better served by group- ing logical components together and moving them into their own folders and files. This makes it easier to work on multiple parts of the application at the same time, as well as to focus on parts of the code that change often versus the parts that don’t. Rust differentiates between applications and libraries. If you create a new applica- tion via cargo new APP_NAME, it will create a main.rs file for you. A new library project is created by using --lib and would create a lib.rs file instead of main.rs. The main difference is that a library crate won’t create an executable (binary). It is meant to provide a public interface to an underlying functionality. A binary crate, on the other hand, where the main.rs file holds the code that starts your application, will create a binary that you can use to execute and start the application. In our case, this is the start of our web server. Everything else—route handlers, errors, and parsing parameters—can be moved into their own logical units and files.
5.2 Rust uses modules to group code together. The mod keyword indicates a new mod- ule, which has to have a name. Let’s see how we group our errors and error han- dling together. mod error { #[derive(Debug)] enum Error { ParseError(std::num::ParseIntError), MissingParameters, QuestionNotFound, } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match *self { Error::ParseError(ref err) => { write!(f, "Cannot parse parameter: {}", err) }, Error::MissingParameters => write!(f, "Missing parameter"), Error::QuestionNotFound => write!(f, "Question not found"), } impl Reject for Error {} } A Rust naming convention dictates using snake_case when naming modules: lower- case letters with an underscore to separate words. Therefore, we named our module error instead of Error. That seems rather easy, and it is. However, our code stops compiling, and we get a few errors (the important pieces are highlighted in bold, and clipped duplicates are indicated via ...): $ cargo build Compiling ch_04 v0.1.0 (/Users/gruberbastian/CodingIsFun/RWD/code/ch_04/final) error[E0433]: failed to resolve: use of undeclared type --> src/main.rs:110:26 | 110 | .map_err(Error::ParseError)?, | ^^^^^ use of undeclared type error[E0433]: failed to resolve: use of undeclared type --> src/main.rs:115:26 | ... error[E0405]: cannot find trait in this scope --> src/main.rs:76:10 | 76 | impl Reject for Error {} | ^^^^^^ not found in this scope | help: consider importing one of these items | 60 | | 60 | | ... use crate::Reject; use warp::reject::Reject; error[E0412]: cannot find type in this scope --> src/main.rs:80:35 | 80 | if let Some(error) = r.find::() { | ^^^^^ not found in this scope | help: consider importing one of these items | 1 | use core::fmt::Error; | 1 | use serde::__private::doc::Error; | 1 | use serde::__private::fmt::Error; | 1 | use serde::de::Error; | and 9 other candidates ... Some errors have detailed explanations: E0405, E0412, E0433. For more information about an error, try . warning: (bin "ch_04") generated 1 warning error: could not compile due to 8 previous errors; 1 warning emitted These two compiler-errors teach us a lot about the module system in Rust: Inside the error module, we can’t access the Reject trait from Warp, but even so we imported it in the same file (error in in line 76). The rest of the application can’t find the Error enum anymore, since it’s now moved into its own module (error in lines 110 and 80). The first one (Reject:notfoundinthisscope) indicates that the modules are operat- ing in a new, separate scope. Everything we need inside them, we have to import. Listing 5.2 Moving the Warp Reject trait from the main.rs imports into our error module ... use warp::{ filters::{body::BodyDeserializeError, cors::CorsForbidden}, http::Method, http::StatusCode, reject::Reject, Filter, Rejection, Reply, }; mod error { use warp::reject::Reject; #[derive(Debug)] enum Error { ParseError(std::num::ParseIntError), MissingParameters, QuestionNotFound, } ... } ... We remove the import of Reject from the beginning of the main.rs file and move it into our error module. Since we don’t use Reject anywhere else, the compiler error disappears, and we are left with a bunch more, which have all the same source. By moving the Error enum behind a module, the rest of the code can’t find it anymore. We need to make sure to update the path to the enum in the rest of the code. The extract_pagination function is a perfect example to work through the process of updating the code to our new module. We start by changing the error return value from Error to error::Error. This is how we access an entity behind a module: by writing down the module name and using the double-colon (::) to access the enum behind it. Listing 5.3 Adding the namespace to import the Error enum from the new error module fn extract_pagination( params: HashMap<String, String> ) -> Result<Pagination, error::Error> { ... Err(Error::MissingParameters) } This, however, brings up a new error: enum is private private enumrustcE0603 // It tells us that the Error enum is private. All types and functions in Rust are private by default, and if we want to expose them, we have to use the pub keyword. mod error { use warp::reject::Reject; #[derive(Debug)] pub enum Error { ParseError(std::num::ParseIntError), MissingParameters, QuestionNotFound, } ... } ... One logical piece is still outside our error module: the return_error function, which would make sense to also include in this module. Listing 5.5 Moving return_error into the error module with all its needed imports ... mod error { use warp::{ filters::{ body::BodyDeserializeError, cors::CorsForbidden, }, reject::Reject, Rejection, Reply, http::StatusCode, }; ... async fn return_error(r: Rejection) -> Result<impl Reply, Rejection> { if let Some(error) = r.find::() { Ok(warp::reply::with_status( error.to_string(), StatusCode::RANGE_NOT_SATISFIABLE, )) } else if let Some(error) = r.find::() { Ok(warp::reply::with_status( error.to_string(), StatusCode::FORBIDDEN, )) } else if let Some(error) = r.find::() { Ok(warp::reply::with_status( error.to_string(), )) } else { 5.1 Modularizing your code 121 StatusCode::UNPROCESSABLE_ENTITY, Ok(warp::reply::with_status( "Route not found".to_string(), StatusCode::NOT_FOUND, )) } } } ... That’s all: the compiler error disappears, and we can move on to the next. We simply have to add error:: in front of every Error enum usage in our code to solve the remaining compiler errors. We move the use of StatusCode, Reply, Rejection, and the two Warp filters we were using uniquely for this function also inside the module and remove them from the overall imports at the beginning of the main.rs file (with the exception of Status- Code, which we also use in our route handler functions). We need to fix two errors after doing this: Make our return_error function public. Call error::return_error in our routes building instead of plain return_error. Listing 5.6 Making the return_error function public for other modules to access it ... mod error { ... pub async fn return_error(r: Rejection) -> Result<impl Reply, Rejection> { println!("{:?}", r); if let Some(error) = r.find::() { Ok(warp::reply::with_status( error.to_string(), StatusCode::UNPROCESSABLE_ENTITY )) ... } } } ... #[tokio::main] async fn main() { let store = Store::new(); let store_filter = warp::any().map(move || store.clone()); ... let routes = get_questions .or(update_question) .or(add_question) .or(add_answer) .or(delete_question) .with(cors) .recover(error::return_error); warp::serve(routes) .run(([127, 0, 0, 1], 3030)) .await; } We accomplished the first step of simplifying and grouping our code. Everything to do with errors goes into its own module from now on. This also has the advantage of seeing which types we need to import from other libraries or our application. It seems that the error module is application code agnostic, which leads to the revelation that this piece of code can be a library, maintained by another team or imported in more than one micro service, for example. Practical folder structure for different use cases The next step is to move code out of the main.rs file and into its own folder or single file. Which direction you go depends on the complexity of code you want to group together. You can have a folder called error, with files for each error type and func- tionality. Or you can have a single file called error.rs that contains the group of code we just put together into a module. Let’s go down the latter route first and create a file called error.rs that lives on the same level as main.rs.
- Assistant
This chapter of the Rust programming book focuses on organizing, structuring, and documenting code using Rust's built-in tools. It covers the following sections:
- Rust's commenting system: Rust values good documentation and has a built-in commenting system that generates code documentation on the fly and tests code in comments.
- Clippy, a linter: Clippy is a widely supported linter in the Rust world, helping with best practices and missing implementations.
- Cargo, a package manager: Rust's package manager, Cargo, helps auto-format code based on predefined rules.
After discussing these tools, the chapter dives into modularizing code and explains how to split code into public and private modules, add comments, write code examples in doc comments, and lint and format code. The chapter covers: