Skip to content

Instantly share code, notes, and snippets.

@shivshank
Forked from anonymous/playground.rs
Created September 3, 2017 00:04
Show Gist options
  • Save shivshank/dd9d2238134e711265a5c12f50b60cc9 to your computer and use it in GitHub Desktop.
Save shivshank/dd9d2238134e711265a5c12f50b60cc9 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);
}
}
}
@shivshank
Copy link
Author

Gist-ing for my notes. I've chosen to accomplish this effect by mirroring the shapes module with functions that yield the shape.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment