Skip to content

Instantly share code, notes, and snippets.

@rcook
Last active March 28, 2021 17:38
Show Gist options
  • Save rcook/4b71acef90a501678db30244b00d79d4 to your computer and use it in GitHub Desktop.
Save rcook/4b71acef90a501678db30244b00d79d4 to your computer and use it in GitHub Desktop.
Traits and polymorphism in Rust
pub trait Frobber {
fn frob(&self) -> String;
}
pub struct Foo {}
impl Frobber for Foo {
fn frob(&self) -> String {
String::from("[Foo.frob]")
}
}
pub struct Bar {}
impl Frobber for Bar {
fn frob(&self) -> String {
String::from("[Bar.frob]")
}
}
use crate::common::*;
/// `frob_it_static` is effectively a _family_ of functions parameterized
/// by type `T`. To a first approximation, the Rust compiler generates a
/// separate function body for unique `T`. Since Rust does not support
/// inheritance/subtype-style polymorphism, the `frobber` argument of
/// `frob_it_static` instantiated for a concrete type, e.g. `Foo`, will
/// accept values _only_ of exactly type `Foo`. This feels very much like
/// Haskell's [_parametric polymorphism_](https://wiki.haskell.org/Polymorphism).
/// This is similar to [templates](https://en.cppreference.com/w/cpp/language/templates)
/// with the addition of [constraints and concepts](https://en.cppreference.com/w/cpp/language/constraints).
/// In `frob_it_static`, `T: Frobber` is a trait constraint specifying that
/// `T` must implement this constraint.
fn frob_it_static<T: Frobber>(frobber: T) -> String {
frobber.frob()
}
/// `concat_frobs_static` is, again, a _family_ of functions. It has two
/// arguments, both of type `T`, and is used to illustrate clearly the point
/// describe in the previous comment: `T` is a single concrete type, i.e.
/// `frobber0` and `frobber1` must be of exactly the same concrete type, which
/// must have an implementation of the `Frobber` trait.
fn concat_frobs_static<T: Frobber>(frobber0: T, frobber1: T) -> String {
format!("{}{}", frobber0.frob(), frobber1.frob())
}
/// `concat_different_frobs_static` is parameterized on two different types
/// that must implement the `Frobber` trait. Thus, in this case, we can pass
/// two different types, or the same type for both `T` and `U`. Side note:
/// I haven't studied code size in much detail, but I would guess that each
/// unique pair of types `(T, U)` must potentially generate a separate function
/// body leading to quadratic code size if every possible type `T` is paired
/// with every possible type `U` (in the absence of any smart code deduplication
/// optimizations).
fn concat_different_frobs_static<T: Frobber, U: Frobber>(frobber0: T, frobber1: U) -> String {
format!("{}{}", frobber0.frob(), frobber1.frob())
}
pub fn run() {
assert_eq!(frob_it_static(Foo {}), "[Foo.frob]");
assert_eq!(frob_it_static(Bar {}), "[Bar.frob]");
assert_eq!(concat_frobs_static(Foo {}, Foo {}), "[Foo.frob][Foo.frob]");
assert_eq!(concat_frobs_static(Bar {}, Bar {}), "[Bar.frob][Bar.frob]");
// The following will not compile as T is resolved to a _specific_ type, i.e. Foo
//assert_eq!(concat_frobs_static(Foo {}, Bar {}), "[Foo.frob][Bar.frob]")
assert_eq!(
concat_different_frobs_static(Foo {}, Foo {}),
"[Foo.frob][Foo.frob]"
);
assert_eq!(
concat_different_frobs_static(Bar {}, Bar {}),
"[Bar.frob][Bar.frob]"
);
assert_eq!(
concat_different_frobs_static(Foo {}, Bar {}),
"[Foo.frob][Bar.frob]"
)
}
use crate::common::*;
/// The `dyn` prefix is optional here (the compiler will warn if it is absent).
/// Regardless, `dyn` is implied and this is inherently dynamically dispatched.
/// The type of the argument must be a reference specified with `&`. You cannot
/// a `Frobber` by value: `Frobber` is a trait so there is no such thing as a
/// _value of type `Frobber`_. Notice how `frob_it_dynamic` has no type arguments.
/// Therefore, this defines a single _concrete_ function as opposed to a family
/// of functions.
fn frob_it_dynamic(frobber: &dyn Frobber) -> String {
frobber.frob()
}
/// Again, `concat_frobs_dynamic` is a single concrete function and not a family
/// of functions since it has no type arguments. Its two arguments are both references
/// to objects implementing `Frobber` and both marked with `dyn`. Since they are
/// `dyn` and references, however, they can be of different concrete types.
fn concat_frobs_dynamic(frobber0: &dyn Frobber, frobber1: &dyn Frobber) -> String {
format!("{}{}", frobber0.frob(), frobber1.frob())
}
pub fn run() {
assert_eq!(frob_it_dynamic(&Foo {}), "[Foo.frob]");
assert_eq!(frob_it_dynamic(&Bar {}), "[Bar.frob]");
assert_eq!(
concat_frobs_dynamic(&Foo {}, &Foo {}),
"[Foo.frob][Foo.frob]"
);
assert_eq!(
concat_frobs_dynamic(&Bar {}, &Bar {}),
"[Bar.frob][Bar.frob]"
);
assert_eq!(
concat_frobs_dynamic(&Foo {}, &Bar {}),
"[Foo.frob][Bar.frob]"
);
}
use crate::common::*;
/// `concat_frobs_from_vec_static` is another family of functions parameterized
/// on types that have implementations of the `Frobber` trait. This function
/// requires a `Vec<T>`: i.e. a homogeneous (all values of the same type) vector
/// of values of type `T`. Note that this function _consumes_ the vector as it
/// takes it by value.
fn concat_frobs_from_vec_static<T: Frobber>(frobbers: Vec<T>) -> String {
// Probably not the most efficient implementation!
frobbers
.iter()
.map(|frobber| frobber.frob())
.collect::<Vec<_>>()
.join(";")
}
/// `concat_frobs_from_vec_dynamic1` is a single concrete function. It consumes
/// a vector of references to objects implementing `Frobber`. Each element of
/// the vector could potentially be a different type. Therefore, this is a
/// _heterogeneous_ vector.
fn concat_frobs_from_vec_dynamic1(frobbers: Vec<&dyn Frobber>) -> String {
// Probably not the most efficient implementation!
frobbers
.iter()
.map(|frobber| frobber.frob())
.collect::<Vec<_>>()
.join(";")
}
/// `concat_frobs_from_vec_dynamic2`&mdash;another single concrete function&mdash;introduces
/// the concept of a _box_. Instead of a vector of references, this is now a vector
/// of _values_ each of which is a _owning reference_ to an object implementing
/// the `Frobber` trait. Note that object ownership is distinctly different from
/// the case of `concat_frobs_from_vec_dynamic1` which takes a vector of references.
/// Both functions _consume_ the vector (since it's passed by value). In addition,
/// `concat_frobs_from_vec_dynamic2` also consumes the _objects) themselves since
/// they are owned by the vector.
fn concat_frobs_from_vec_dynamic2(frobbers: Vec<Box<dyn Frobber>>) -> String {
// Probably not the most efficient implementation!
frobbers
.iter()
.map(|frobber| frobber.frob())
.collect::<Vec<_>>()
.join(";")
}
pub fn run() {
assert_eq!(
concat_frobs_from_vec_static(vec![Foo {}, Foo {}]),
"[Foo.frob];[Foo.frob]"
);
assert_eq!(
concat_frobs_from_vec_static(vec![Bar {}, Bar {}]),
"[Bar.frob];[Bar.frob]"
);
// The following will not compile as T is resolved to a _specific_ type, i.e. Foo
//assert_eq!(concat_frobs_from_vec_static(vec![Foo {}, Bar {}]), "[Foo.frob];[Bar.frob]")
assert_eq!(
concat_frobs_from_vec_dynamic1(vec![&Foo {}, &Foo {}]),
"[Foo.frob];[Foo.frob]"
);
assert_eq!(
concat_frobs_from_vec_dynamic1(vec![&Bar {}, &Bar {}]),
"[Bar.frob];[Bar.frob]"
);
assert_eq!(
concat_frobs_from_vec_dynamic1(vec![&Foo {}, &Bar {}]),
"[Foo.frob];[Bar.frob]"
);
assert_eq!(
concat_frobs_from_vec_dynamic2(vec![Box::new(Foo {}), Box::new(Foo {})]),
"[Foo.frob];[Foo.frob]"
);
assert_eq!(
concat_frobs_from_vec_dynamic2(vec![Box::new(Bar {}), Box::new(Bar {})]),
"[Bar.frob];[Bar.frob]"
);
assert_eq!(
concat_frobs_from_vec_dynamic2(vec![Box::new(Foo {}), Box::new(Bar {})]),
"[Foo.frob];[Bar.frob]"
)
}
The MIT License (MIT)
Copyright (c) 2020 Richard Cook
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
mod common;
mod example0;
mod example1;
mod example2;
fn main() {
example0::run();
example1::run();
example2::run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment