liveBook · Manning

Impl block

As explained in Rust in Action: Systems programming concepts and techniques

The impl keyword is Rust's reserved keyword for associating implementations, including trait implementations, with types.

An impl block associates methods or trait implementations with a Rust type. It is written separately from the struct or enum definition, because Rust has no class keyword. section 3.3 section 3.6.1

Use an impl block to:

  • Define methods that operate on a struct or enum, such as File::read. section 3.3 section 3.5
  • Create constructors by convention with methods such as new() and new_with_data(). section 3.3.1
  • Implement a trait for a specific type with syntax such as impl Read for File. section 3.6.1
  • Keep implementation details private unless items are declared public with pub. section 3.0 section 3.9

Constructing and reading a File

struct File { name: String, data: Vec<u8> } impl File { fn new(name: &str) -> File { File { name: String::from(name), data: Vec::new() } } fn read(self: &File, save_to: &mut Vec<u8>) -> usize { let mut data = self.data.clone(); let length = data.len(); save_to.reserve(length); save_to.append(&mut data); length } } let file = File::new("f3.txt"); section 3.3.1 section 3.3.1

Figure 3.2 Illustrating syntactic differences between Rust and most object oriented languages. Within Rust, methods are defined separately from fields.

Compare Rust's separate type and method blocks with the syntax used by class-oriented languages. section 3.3

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Explains separate syntax and working method and trait examples, without covering advanced implementation details.
Examples
Demonstrates File constructors and methods, a Read implementation, and methods attached to an event enum.
What it assumes
Assumes familiarity with structs and enums while teaching methods, constructors, and trait attachment through concrete programs.
What you can do after
Build methods and trait implementations for Rust structs and enums using separate impl blocks.
How it connects
Connects impl blocks with structs, enums, methods, constructors, traits, privacy, and Result.

Also explained in

Compare how 3 books explain impl block →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.