TL ; DR:
A struct can keep an object of another struct in a field. It passes work on to that object. A Car has an Engine. This is composition.
struct Car {
engine: Engine, // a Car has an Engine
}
impl Car {
fn start(&self) {
self.engine.start(); // the Car asks its Engine
}
}
Full lesson:
Things are often made of other things. A car has an engine. A phone has a battery.
Code works the same way. One struct keeps an object of another struct in a field. This is called composition.
The outer object passes some work on to its part. Car's start just calls the engine's start. This is called delegation.
Has-a or is-a?
Rust has no inheritance, so you have seen this already. In Inheritance, Puppy kept a Dog in a field. Languages with classes would say a Puppy is a Dog. A Car is not an Engine, though. A car has an engine, so Car keeps one in a field. Rust passes on no methods: Car chooses what to pass on.
Why it helps
- The engine stays private. Code outside talks to the car, never to the engine.
- Each struct does one job.
Engineknows how to start.Carknows its name and how to drive. - A part can be replaced. A car with a new engine is still the same car.
Fields are private by default, as in Access Modifiers. The car's new function builds its engine too.
Your task
The Engine struct is ready. Car already has a name and a drive method.
Give the Car struct an engine field. Build the engine in the car's new function.
Then write Car's start method. It calls the engine's start.
The program makes a car named "Rocket". It starts the car, then drives it.
Expected output:
Engine started
Rocket is drivingFree plan: 30 tutor messages. Premium is unlimited.
