Last active
August 29, 2024 11:42
-
-
Save jmsdnns/5bfe9750aaf38979434c3b08de2a6d2b to your computer and use it in GitHub Desktop.
Basic example for understanding Rust traits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![allow(clippy::upper_case_acronyms)] | |
// a trait for describing vehicles that can move on land | |
trait LandCapable { | |
// a function with no implementation acts as an interface | |
//fn drive(&self); | |
// default imlpementation | |
fn drive(&self) { | |
println!("Default drive"); | |
} | |
} | |
// takes an implementation of LandCapable and calls the drive function | |
fn road_trip(vehicle: &impl LandCapable) { | |
vehicle.drive(); | |
} | |
// one type of LandCapable struct that does not implement drive() | |
struct Sedan; | |
impl LandCapable for Sedan {} | |
// another type of LandCapable struct that does implement drive() | |
struct SUV; | |
impl LandCapable for SUV { | |
fn drive(&self) { | |
println!("SUV is driving"); | |
} | |
} | |
// a trait for describing vehicles that can move on water | |
trait WaterCapable { | |
fn float(&self) { | |
println!("Default float"); | |
} | |
} | |
// a super trait made from combining two other traits | |
trait Amphibious: WaterCapable + LandCapable {} | |
// a struct that implements the super trait | |
struct Hovercraft; | |
impl Amphibious for Hovercraft {} | |
impl LandCapable for Hovercraft {} | |
impl WaterCapable for Hovercraft { | |
fn float(&self) { | |
println!("Hovercraft is floating"); | |
} | |
} | |
// a funciton that takes the super trait as a parameter | |
fn traverse_frozen_lake(vehicle: &impl Amphibious) { | |
vehicle.drive(); | |
vehicle.float(); | |
} | |
// Has the following output: | |
// Default drive | |
// SUV is driving | |
// Default drive | |
// Hovercraft is floating | |
fn main() { | |
let car = Sedan; | |
road_trip(&car); | |
let suv = SUV; | |
road_trip(&suv); | |
let hc = Hovercraft; | |
traverse_frozen_lake(&hc); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment