4 Introductory patterns

 

This chapter covers

  • Understanding resource acquisition is initialization
  • Passing arguments by value versus reference
  • Using constructors
  • Understanding object member visibility and access
  • Handling errors
  • Global state handling with lazy-static.rs, OnceCell, and static_init

Now we’re ready to dive into some more concrete patterns. We begin by reviewing some elementary topics: RAII, passing values, constructors, and visibility. Then we’ll move on to slightly more complex subjects: error handling and global variables. Although the chapter discusses many topics, it focuses on bite-size patterns, which we’ll use a lot.

This chapter also introduces crates, which are Rust libraries built by the community. The Rust language is built on crates, which are crucial parts of Rust programming; you won’t get far without using them. Although it’s possible to go full not-invented-here syndrome and eschew crates, I don’t recommend this approach. Even the largest, best-funded organizations rely heavily on open source software to build their stacks to varying degrees.

You’ll quickly find when working with Rust that the standard library is somewhat bare and doesn’t include many of the features you might expect from a modern language. These limits are by design; the Rust team chose to keep the standard library minimal and instead rely on crates to provide additional functionality. This approach has several benefits:

4.1 Resource acquisition is initialization

4.1.1 Understanding RAII in C and C++

4.1.2 A tour of RAII in Rust

4.1.3 Summarizing RAII in Rust

4.2 Passing arguments by value vs. reference

4.2.1 Passing by value

4.2.2 Passing by reference

4.2.3 When to do what: Passing by value vs. reference

4.3 Constructors

4.4 Object-member visibility and access

4.5 Error handling

4.6 Global state

4.6.1 lazy-static.rs

4.6.2 once_cell

4.6.3 static_init

4.6.4 std::cell::OnceCell

Summary