Created
January 6, 2020 14:42
-
-
Save rust-play/4a9bafd8f322ffa22d4f33cdd8921422 to your computer and use it in GitHub Desktop.
Code shared from the Rust 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
#![feature(trait_alias)] | |
#[derive(Debug, Clone)] | |
struct Context { | |
a: A, | |
b: B, | |
} | |
#[derive(Debug, Clone)] | |
struct A(i32); | |
#[derive(Debug, Clone)] | |
struct B(i32); | |
impl From<Context> for A { | |
fn from(ctx: Context) -> Self { | |
ctx.a | |
} | |
} | |
impl From<Context> for B { | |
fn from(ctx: Context) -> Self { | |
ctx.b | |
} | |
} | |
mod cw { | |
pub(super) trait CallWith<Ctx, Args> { | |
fn call_with(&self, ctx: Ctx); | |
} | |
impl<A: From<Ctx>, F: Fn(A), Ctx> CallWith<Ctx, (A,)> for F { | |
fn call_with(&self, ctx: Ctx) { | |
self(A::from(ctx)); | |
} | |
} | |
impl<A: From<Ctx>, B: From<Ctx>, F: Fn(A, B), Ctx: Clone> CallWith<Ctx, (A, B)> for F { | |
fn call_with(&self, ctx: Ctx) { | |
self(A::from(ctx.clone()), B::from(ctx)); | |
} | |
} | |
} | |
trait CallWith<A> = cw::CallWith<Context, A>; | |
fn call<T>(ctx: Context, f: impl CallWith<T>) { | |
f.call_with(ctx) | |
} | |
fn main() { | |
let ctx = Context {a: A(1), b: B(2) }; | |
call(ctx, |a: A, b: A| println!("{:?}", b)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment