Skip to content

Instantly share code, notes, and snippets.

Created September 3, 2017 00:04
Show Gist options
  • Save anonymous/7289a8496f39c679ec688b7dbcb94137 to your computer and use it in GitHub Desktop.
Save anonymous/7289a8496f39c679ec688b7dbcb94137 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
fn main() {
use shape_args::Dot;
draw(Dot(5.5));
}
// I need a function that works like this:
// pub fn draw<D: Drawable, T: Into<D>>(d: T) {
// but where Rust can always infer what D is
pub fn draw<T: DrawableArg>(d: T) {
d.convert().execute();
}
// I've chosen to solve that via associated types
pub trait DrawableArg {
type Target: Drawable;
fn convert(self) -> Self::Target;
}
pub trait Drawable {
fn execute(&self);
}
// Mirrors shapes module but allows user to specify shapes with function-like
// notation
mod shape_args {
use super::{shapes, DrawableArg};
pub struct Dot(pub f32);
impl DrawableArg for Dot {
type Target = shapes::Dot;
fn convert(self) -> Self::Target {
shapes::Dot {
x: self.0
}
}
}
}
mod shapes {
use super::Drawable;
pub struct Dot {
pub x: f32
}
impl Drawable for Dot {
fn execute(&self) {
println!("{}", self.x);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment