Intro Implementation Blocks
Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 1 of 61.
In Rust, structs define what data a type holds, but they don't define what that type can do. To give a struct behavior, we use implementation blocks with the impl keyword.
An implementation block connects functions (called methods) to a specific struct. Here's the basic structure:
struct Dog {
name: String,
age: u8,
}
impl Dog {
fn bark(&self) {
println!("{} says woof!", self.name);
}
}
The impl Dog block tells Rust that everything inside belongs to the Dog struct. This separation keeps your data definition clean while allowing you to add as many methods as needed in the implementation block.
To call a method, use dot notation on an instance:
fn main() {
let my_dog = Dog {
name: String::from("Rex"),
age: 3,
};
my_dog.bark(); // Output: Rex says woof!
}
This pattern of separating data (the struct) from behavior (the impl block) is fundamental to organizing Rust code. In the upcoming lessons, we'll explore how methods access struct data through the &self parameter you see in the example above.
Challenge
EasyCreate a Cat struct with two fields: name (String) and lives (u8).
Add an implementation block for Cat with a method called meow that takes &self and prints the cat's name followed by " says meow!".
You will receive two inputs:
- First line: the cat's name (String)
- Second line: the number of lives (u8)
Create a Cat instance with the provided values and call the meow method on it.
Expected output format:
{name} says meow!Cheat sheet
Implementation blocks connect methods to structs using the impl keyword:
struct Dog {
name: String,
age: u8,
}
impl Dog {
fn bark(&self) {
println!("{} says woof!", self.name);
}
}
The impl block separates data definition (struct) from behavior (methods). Methods are called using dot notation:
let my_dog = Dog {
name: String::from("Rex"),
age: 3,
};
my_dog.bark(); // Output: Rex says woof!
Methods use the &self parameter to access struct data.
Try it yourself
use std::io;
// TODO: Define the Cat struct with 'name' (String) and 'lives' (u8) fields
// TODO: Add an implementation block for Cat with a 'meow' method
fn main() {
let mut name = String::new();
io::stdin().read_line(&mut name).expect("Failed to read line");
let name = name.trim().to_string();
let mut lives_input = String::new();
io::stdin().read_line(&mut lives_input).expect("Failed to read line");
let lives: u8 = lives_input.trim().parse().expect("Failed to parse lives");
// TODO: Create a Cat instance and call the meow method
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Methods and Behavior
Intro Implementation BlocksThe Self ParameterMutable MethodsAssociated FunctionsMultiple Implementation BlocksMethod ChainingRecap - Rectangle Actions4Project: Virtual Pet
Defining the PetFeeding the Pet7Standard Traits
The Debug TraitThe Display TraitClone and CopyEquality TraitsRecap - Printable Point10Project: Document System
The Draw TraitText Component2Encapsulation and Modules
Modules BasicsThe Public KeywordPrivate FieldsGettersSettersRecap - Secure Locker5Generics
Generic StructsGeneric MethodsMultiple Generic TypesGeneric FunctionsRecap - Coordinate Point8Traits as Bounds
Trait Bounds SyntaxMultiple BoundsThe Where ClauseReturning Types with TraitsRecap - Generic Printer11Design Patterns in Rust
Newtype PatternCompositionThe Drop TraitFrom and IntoRecap - Smart Pointer Mock