Recap - Media Player
Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 34 of 61.
Challenge
EasyLet's build a simple media player system that demonstrates how different media types can share a common interface through traits!
You'll organize your code across three files:
playable.rs: Define a publicPlayabletrait with aplay(&self)method that prints output when called. This trait represents the shared capability that all media types will have.media.rs: Create two public structs that implement your trait:Audio— with a publictitlefield (String) that printsPlaying audio: {title}when playedVideo— with a publictitlefield (String) that printsPlaying video: {title}when played
main.rs: Bring your modules together and create instances of both media types using the inputs provided. Call theplaymethod on each to demonstrate how the same trait produces different outputs based on the media type.
Your output should follow this format:
Playing audio: {audio_title}
Playing video: {video_title}For example, with inputs Bohemian Rhapsody and The Matrix:
Playing audio: Bohemian Rhapsody
Playing video: The MatrixYou will receive two inputs: an audio title and a video title.
Try it yourself
mod playable;
mod media;
use media::{Audio, Video};
use playable::Playable;
fn main() {
// Read input
let mut audio_title = String::new();
std::io::stdin().read_line(&mut audio_title).expect("Failed to read line");
let audio_title = audio_title.trim().to_string();
let mut video_title = String::new();
std::io::stdin().read_line(&mut video_title).expect("Failed to read line");
let video_title = video_title.trim().to_string();
// TODO: Create an Audio instance with audio_title
// TODO: Create a Video instance with video_title
// TODO: Call play() on both instances
}
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 Mock3Advanced Enums
Enums with DataMethods on EnumsMatching Data VariantsThe Option Enum RevisitedRecap - Shape Enum6Traits Definition
What is a Trait?Implementing TraitsDefault ImplementationsOverriding DefaultsTraits with ParametersRecap - Media Player