-
-
Save shivshank/dd9d2238134e711265a5c12f50b60cc9 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
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
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
Gist-ing for my notes. I've chosen to accomplish this effect by mirroring the shapes module with functions that yield the shape.