Chapter 2: Laying the foundation
This introduction frames the chapter’s Rust foundations and their value for building adaptable web services.
After this chapter you will be able to
- Transferable Rust Ecosystem Foundations. Explain how Rust and ecosystem knowledge can remain useful across web frameworks and when a project’s needs change.
- Tool assisted Rust learning. Explain how the compiler, other tools, and documentation help you work in Rust without knowing every language detail in advance.
- Struct and implementation blocks. Explain how to define a Question type and add a constructor and behavior to it.
- Question identifier newtype. Explain how QuestionId wraps a string and why using a distinct type is useful.
- Optional values and fields. Explain how Option represents a value that may be absent and why optional struct fields must be marked explicitly.
- Checking Option values. Describe how match and is_some can check an Option value.
- Compiler Error Diagnosis. Explain why to start with the first compiler error and identify the type mismatches in the Question example.
- Rust Documentation Navigation. Describe where to find a type overview and its available methods and implementations in the Rust documentation.
- Owned Strings and string views. Distinguish String from &str in terms of ownership, mutability, and representation.
- String type selection rules. Apply the section’s rules of thumb for choosing String or &str in struct fields and function parameters.
- String and slice assignment. Distinguish assigning an &str from assigning a String in the examples, including what happens to the original variable.
- Moving ownership into functions. Trace how passing address by value to add_postal_code affects ownership and how the updated String is returned.
- Mutable reference borrowing. Explain how passing a mutable reference lets add_postal_code modify address while the caller retains ownership.
- Traits and shared behavior. Explain how traits provide shared or standardized behavior and enable generic code to work with types that have that behavior.
- Display and Debug formatting. Distinguish Display and Debug formatting, including the format placeholders used for each.
- Custom formatting trait implementations. Describe how the example implements Display for Question and uses derive for Debug.
- QuestionId string conversion. Explain how FromStr creates a QuestionId from a string slice and how its call differs from to_string.
- Result variants and signature. Explain how Result represents success or failure and how a function declares its value and error types.
- Result error handling. Describe what expect and unwrap do on failure and explain the section’s recommendation for handling errors in production.
- Result versus Option. Distinguish Result from Option using the question’s optional tags and required ID as examples.
- Rust Asynchronous Building Blocks. Distinguish Rust’s built-in asynchronous syntax and Future type from the runtime needed for asynchronous background work.
- Web Framework Design Choices. Explain what the chosen web framework supplies or determines and why its design decisions matter.
- Asynchronous Server Code Markers. Describe what the runtime annotation, asynchronous main function, and .await indicate in the server example.
- Nonblocking request handling. Explain how a server can make progress on other requests while a slow operation is unfinished, contrasting this with the blocking minimal-tcp example.
- Asynchronous environment ingredients. Describe the four ingredients the section identifies for an asynchronous programming environment and their roles.
- Rust asynchronous provision. Distinguish the asynchronous ingredients Rust supplies from those it does not supply, and state why Rust dropped green threads.
- Async ecosystem and runtime choice. Explain which async building blocks Rust supplies and why an application chooses a runtime.
- Async syntax and futures. Describe how async and await relate to a Future and what its poll method returns.
- Awaiting HTTP Request Futures. Describe how the Reqwest HTTP example uses a future and await with the runtime.
- Async Syntax State Machine. Explain the intent of async/await syntax and the state-machine transformation described in the section.
- Future polling and output. Explain how polling a future indicates its readiness and yields its output.
- Runtime responsibility for polling. Explain the runtime’s role in starting progress on Rust futures and contrast it with the examples from Go or JavaScript.
- Async runtime responsibilities. Describe the runtime’s responsibilities for futures, threads, and asynchronous kernel work, including Mio’s role in Tokio.
- Async network request flow. Trace the section’s async network request from a future being polled through kernel notification and resumed computation.
- Warp selection and boundaries. Explain why the book chooses Warp and why recognizing framework-dependent code matters.
- Warp server stack. Describe the roles of Tokio, Hyper, and Warp in handling incoming requests.
- Minimal server setup. Describe how the project adds and runs the Warp server and how to check its response.
Section by section
Introduction
This introduction frames the chapter’s Rust foundations and their value for building adaptable web services.
- Transferable Rust Ecosystem Foundations: Explain how Rust and ecosystem knowledge can remain useful across web frameworks and when a project’s needs change.
Why it matters: These foundations can help you adapt your web service rather than tying your understanding to one framework. - Operating System Knowledge Benefits: Describe the role of operating system knowledge in learning Rust for web services.
Why it matters: This distinction helps you balance learning Rust syntax with broadening your systems knowledge.
Key terms: web framework, Rust ecosystem, crates, operating systems, allocate memory, execute functions
2.1 Following the Rust playbook
This section frames learning Rust as a practical process of using tools and documentation while accounting for the initial effort of strict typing.
- Tool assisted Rust learning: Explain how the compiler, other tools, and documentation help you work in Rust without knowing every language detail in advance.
Why it matters: You can make progress in Rust without mastering every detail before you start. - Strict typing upfront effort: Explain why Rust's strict typing can make initial work on a simple program or JSON fetch take longer.
Why it matters: This helps set expectations for the initial work of modeling data or fetching JSON in Rust.
Key terms: compiler, Clippy, docs.rs, strictly typed, types, unknown values
2.1.1 Modeling your resources with structs
This section models a question-and-answer service and introduces Rust structs, implementation blocks, and the New Type pattern.
- Resource and question models: Describe how the service’s resources and the Question fields are identified before implementing routes.
Why it matters: Identifying resources and their behavior gives the API a concrete model to build around. - Struct and implementation blocks: Explain how to define a Question type and add a constructor and behavior to it.
Why it matters: This is the basic way the service defines its own data and associated behavior. - Question identifier newtype: Explain how QuestionId wraps a string and why using a distinct type is useful.
Why it matters: A distinct ID type makes a parameter’s purpose explicit rather than treating every identifier as an interchangeable string.
Key terms: resources, models, Question, id, title, content, struct, fields, impl block, new
2.1.2 Understanding options
This section explains how Rust represents optional values and checks whether they are present.
- Optional values and fields: Explain how Option represents a value that may be absent and why optional struct fields must be marked explicitly.
Why it matters: Explicit optionality makes missing values part of the type rather than an unexpected null. - Checking Option values: Describe how match and is_some can check an Option value.
Why it matters: These checks let code respond deliberately to values that may be missing. - Pattern matching beyond options: Describe a capability of Rust pattern matching beyond checking an Option.
Why it matters: Pattern matching can express more than a simple choice between cases. - Rust Playground experimentation: Describe how the Rust Playground helps test small Rust ideas.
Why it matters: The Playground makes it easy to experiment with examples without setting up a project.
Key terms: Option, Some, None, Option<Type>, match, is_some, pattern matching, destructuring, structs, enums
2.1.3 Using documentation to solve errors
This section uses a failing Question example to introduce Rust compiler errors, associated functions, and documentation navigation.
- Associated Functions and Methods: Distinguish associated functions from methods using their parameters and call syntax.
Why it matters: This distinction helps you recognize how to define and call behavior on Rust types. - Compiler Error Diagnosis: Explain why to start with the first compiler error and identify the type mismatches in the Question example.
Why it matters: Starting at the first error helps you avoid chasing messages that may disappear when the underlying mistake is fixed. - Rust Documentation Navigation: Describe where to find a type overview and its available methods and implementations in the Rust documentation.
Why it matters: Knowing where to look helps you use the documentation to investigate a type error. - Local Documentation Availability: Describe how Rust documentation can be made available locally and what generated project documentation includes.
Why it matters: Local and generated documentation gives you access to relevant API information without relying solely on online browsing.
Key terms: associated functions, methods, &self, ::, compiler errors, QuestionId, &str, String, trait implementations, auto trait implementations
2.1.4 Handling strings in Rust
This section contrasts Rust’s owned, resizable String with read-only string slices and introduces the memory concepts behind them.
- Owned Strings and string views: Distinguish String from &str in terms of ownership, mutability, and representation.
Why it matters: This distinction helps you choose how to represent and access text in Rust. - String type selection rules: Apply the section’s rules of thumb for choosing String or &str in struct fields and function parameters.
Why it matters: These rules provide a practical starting point for designing text fields and function parameters. - String slice data type: Describe what str is and how it relates to &str.
Why it matters: This clarifies what the ampersand in &str refers to. - Stack and heap overview: Describe the section’s basic distinction between stack and heap storage and its relevance to string memory.
Why it matters: A basic memory model can help you make sense of later compiler errors.
Key terms: String, &str, vector, u8, struct, parameter type, str, string slice, UTF-8, stack
2.1.5 Taking an excursion into moving, borrowing, and ownership
This section explains Rust ownership through String and &str assignments and two ways to pass a String to a function.
- Ownership and memory safety: Explain the memory-management motivation for Rust’s ownership concept.
Why it matters: Ownership is Rust’s alternative approach to managing memory safely. - String and slice assignment: Distinguish assigning an &str from assigning a String in the examples, including what happens to the original variable.
Why it matters: This distinction explains why the same assignment pattern works for both &str variables but makes the original String unavailable. - Moving ownership into functions: Trace how passing address by value to add_postal_code affects ownership and how the updated String is returned.
Why it matters: Understanding the move explains why the returned String must be used instead of the original address. - Mutable reference borrowing: Explain how passing a mutable reference lets add_postal_code modify address while the caller retains ownership.
Why it matters: Borrowing provides a way to modify a String in a function without losing the caller’s ability to use it afterward.
Key terms: ownership, garbage collector, String, &str, string slice, single-ownership principle, uninit, mut, push_str, variable shadowing
2.1.6 Using and implementing traits
This section uses traits, documentation, and compiler errors to fix and format a Question, then implements string conversion for its identifier.
- Traits and shared behavior: Explain how traits provide shared or standardized behavior and enable generic code to work with types that have that behavior.
Why it matters: Traits let different types participate in the same operations without being the same type. - Question type mismatch corrections: Describe how the example uses documentation to fix the string and tags type mismatches in Question.
Why it matters: Matching the declared field types resolves the compiler errors in the example. - Display and Debug formatting: Distinguish Display and Debug formatting, including the format placeholders used for each.
Why it matters: Choosing the right formatting trait lets you print primitives and inspect more complex values. - Custom formatting trait implementations: Describe how the example implements Display for Question and uses derive for Debug.
Why it matters: Custom types need suitable trait implementations before they can be formatted in the desired way. - QuestionId string conversion: Explain how FromStr creates a QuestionId from a string slice and how its call differs from to_string.
Why it matters: A conversion trait provides a convenient interface while keeping the ID's representation behind its type. - Macro code generation: Describe how the section identifies function-like macros and what macros do before compilation produces a binary.
Why it matters: Recognizing macro calls helps explain examples such as println! and vec!.
Key terms: traits, shared behavior, generic, ToString, to_string, QuestionId, Option, Some, Vec, Display
2.1.7 Handling results
This section explains Rust’s Result type, how to handle success and failure, and when to use Result instead of Option.
- Result variants and signature: Explain how Result represents success or failure and how a function declares its value and error types.
Why it matters: Result makes both successful values and errors explicit in a function’s return type. - Result error handling: Describe what expect and unwrap do on failure and explain the section’s recommendation for handling errors in production.
Why it matters: Handling failures explicitly helps prevent an error from crashing the application. - Result versus Option: Distinguish Result from Option using the question’s optional tags and required ID as examples.
Why it matters: The distinction helps express whether missing data is acceptable or a failure that needs attention.
Key terms: Result, Ok, Err, Result<T, E>, expect, unwrap, panic, match, Option, Question
2.2 Creating our web server
This section recaps Rust’s web-server building blocks and highlights how a framework and runtime shape an asynchronous server.
- Rust Asynchronous Building Blocks: Distinguish Rust’s built-in asynchronous syntax and Future type from the runtime needed for asynchronous background work.
Why it matters: This distinction helps you see what Rust supplies and what an asynchronous web service still needs. - Web Framework Design Choices: Explain what the chosen web framework supplies or determines and why its design decisions matter.
Why it matters: Choosing a framework means accepting decisions that affect how the server runs and handles requests. - Asynchronous Server Code Markers: Describe what the runtime annotation, asynchronous main function, and .await indicate in the server example.
Why it matters: These markers give you a first visual guide to the asynchronous server example.
Key terms: runtime, asynchronous code blocks, Future, web framework, HTTP, TCP, UDP, route handlers, #[tokio::main], main
2.2.1 Handling multiple requests at once
This section explains how asynchronous execution helps servers handle multiple requests and identifies the components Rust provides for an asynchronous environment.
- Nonblocking request handling: Explain how a server can make progress on other requests while a slow operation is unfinished, contrasting this with the blocking minimal-tcp example.
Why it matters: This explains how a server can avoid leaving other clients waiting during slow operations. - Green thread management: Distinguish green threads from operating-system-managed threads as described in the section.
Why it matters: The distinction helps explain the runtime's role in managing asynchronous work. - Asynchronous environment ingredients: Describe the four ingredients the section identifies for an asynchronous programming environment and their roles.
Why it matters: These ingredients give you a framework for understanding what an asynchronous system needs. - Rust asynchronous provision: Distinguish the asynchronous ingredients Rust supplies from those it does not supply, and state why Rust dropped green threads.
Why it matters: This distinction explains why a Rust asynchronous application needs components beyond the language itself.
Key terms: blocking, runtime, yield, green threads, user space, kernel, kernel asynchronous read-and-write API, syntax, type, state
2.2.2 Rust’s asynchronous environment
This section introduces Rust’s async ecosystem, its runtime choices, and the basic roles of async, await, and Future.
- Async ecosystem and runtime choice: Explain which async building blocks Rust supplies and why an application chooses a runtime.
Why it matters: This explains why choosing a runtime is an important part of building an async Rust application. - Async syntax and futures: Describe how async and await relate to a Future and what its poll method returns.
Why it matters: These basics connect Rust’s async syntax to the type representing an ongoing operation.
Key terms: runtime, async kernel API, Tokio, async-std, Mio, async, await, Future, poll, Pending
2.2.3 Rust’s handling of async/await
This section introduces Rust’s async/await syntax through an HTTP request and explains dependency feature flags and the syntax’s state-machine model.
- Crate Feature Flags: Explain why crate feature flags are used and how the example enables Tokio’s features.
Why it matters: Feature selection helps you include the crate functionality your project needs without necessarily pulling in everything. - Awaiting HTTP Request Futures: Describe how the Reqwest HTTP example uses a future and await with the runtime.
Why it matters: Recognizing a future and awaiting it lets you use asynchronous library calls to obtain their results. - Async Syntax State Machine: Explain the intent of async/await syntax and the state-machine transformation described in the section.
Why it matters: The synchronous-looking syntax can otherwise obscure the asynchronous nature of the work.
Key terms: feature flags, Cargo.toml, full, async, await, Future, runtime, reqwest::get, async/await, state machine
2.2.4 Using Rust’s Future type
This section explains the basic behavior of Rust futures, their trait-based flexibility, and the runtime’s role in polling them.
- Future polling and output: Explain how polling a future indicates its readiness and yields its output.
Why it matters: This gives you a basic model for how an awaited value becomes available. - Runtime responsibility for polling: Explain the runtime’s role in starting progress on Rust futures and contrast it with the examples from Go or JavaScript.
Why it matters: This distinction explains why a Rust future needs a runtime to make progress. - Future trait flexibility: Describe why Future being a trait is useful for types in a program.
Why it matters: This shows that futures are defined through a trait rather than limited to one concrete type.
Key terms: Future, Output, poll, Pending, Ready, runtime, trait
2.2.5 Choosing a runtime
This section introduces Rust async runtimes, the choice of Tokio, and how an async network request moves through runtime components.
- Runtime selection in Rust: Explain why Rust’s lack of a bundled runtime allows developers to choose one for their needs, and why the example uses Tokio.
Why it matters: The runtime you choose is part of tailoring an asynchronous service to its environment. - Async runtime responsibilities: Describe the runtime’s responsibilities for futures, threads, and asynchronous kernel work, including Mio’s role in Tokio.
Why it matters: These responsibilities make the runtime central to how an async web service executes. - Async network request flow: Trace the section’s async network request from a future being polled through kernel notification and resumed computation.
Why it matters: Following the request shows how the runtime’s components cooperate while network work is in progress.
Key terms: runtime, Tokio, Future, polling, kernel, Mio, async, executor, poll, socket
2.2.6 Choosing a web framework
This section compares Rust web frameworks, explains the choice of Warp and its underlying stack, and incorporates a minimal Warp server into the project.
- Rust framework tradeoffs: Compare the frameworks discussed in terms of their features and design approaches.
Why it matters: Frameworks differ in how much functionality and design direction they provide. - Warp selection and boundaries: Explain why the book chooses Warp and why recognizing framework-dependent code matters.
Why it matters: Recognizing the framework boundary makes it easier to apply the book's code to a different choice. - Warp server stack: Describe the roles of Tokio, Hyper, and Warp in handling incoming requests.
Why it matters: The stack shows which part of the server handles the runtime, HTTP, and routing responsibilities. - Closure in Warp map: Explain the role of the closure in the example's map call.
Why it matters: The closure is the part of the example that can make values available for processing inside map. - Minimal server setup: Describe how the project adds and runs the Warp server and how to check its response.
Why it matters: These steps turn the existing project into a running local web server.
Key terms: Actix Web, Rocket, Warp, Axum, framework agnostic, Tokio, Hyper, runtime, route handlers, closure
2.3 Summary
Where this is used later
- Installing and using Clippy (chapter 5) · Develops the use of Clippy to improve the codebase.
- Preparing a set of test data (chapter 4) · The question model provides the shape of the test data.
- Creating types for our API responses (chapter 8) · Optional fields can represent API response data that may be absent.
- Parsing query parameters (chapter 4) · Options and the Some and None cases
- Creating the user concept (chapter 9) · Using Option to represent a value that may be absent
- Documenting your code (chapter 5) · Project documentation provides context for documenting the codebase.
- Setting up a mock database (chapter 4) · Moving, borrowing, and ownership.
- Reading from the fake database (chapter 4) · Moving values and ownership
Concepts explained in this chapter
- ownershipRust's ownership system governs how values are owned, borrowed, and dropped to ensure memory safety.
- static methodAn associated function is a function defined for a Rust type that is called through the type rather than a value instance.
- DisplayDisplay is a Rust formatting trait for representing values in human-readable, user-facing form.
- await syntaxAwait syntax in Rust suspends an asynchronous computation until its future can make progress or complete.
- async syntaxAsync syntax is Rust syntax for marking functions or code blocks as asynchronous computations.
- borrowingRust’s mechanism for temporarily accessing a value through a reference without transferring its ownership.
- documentationSoftware documentation is written information describing software, its behavior, or how to use it.
- web application frameworkA web framework is a software framework that provides abstractions and components for building web applications or services.
- pollFuture::poll is the trait method a runtime calls to advance a future's computation.
- mutable referenceA Rust reference that permits mutation of the value it refers to, subject to Rust’s borrowing rules.
- Future::OutputFuture::Output is the associated type specifying the value produced when a future completes.
- route handlerA route handler is a function or component in the example application that processes a request directed to a particular route.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
