Skip to content

Instantly share code, notes, and snippets.

@jeffs

jeffs/switch.rs Secret

Last active August 23, 2021 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffs/3604fd82da0d5a1b7bb212a9b1ca2efc to your computer and use it in GitHub Desktop.
Save jeffs/3604fd82da0d5a1b7bb212a9b1ca2efc to your computer and use it in GitHub Desktop.
nested-polymorphism-overload-rs
pub struct Ball;
pub struct Game;
pub struct Tantrum;
pub trait Thrown {
fn thrown(&self) -> char;
}
impl Thrown for Ball {
fn thrown(&self) -> char {
'⚾'
}
}
impl Thrown for Game {
fn thrown(&self) -> char {
'🤞'
}
}
impl Thrown for Tantrum {
fn thrown(&self) -> char {
'👿'
}
}
pub struct Athlete {}
impl Athlete {
pub fn throw<T: Thrown>(&self, thing: T) -> char {
thing.thrown()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_athlete_throw() {
let athlete = Athlete {};
assert_eq!('⚾', athlete.throw(Ball));
assert_eq!('🤞', athlete.throw(Game));
assert_eq!('👿', athlete.throw(Tantrum));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment