Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created January 6, 2020 14:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/4a9bafd8f322ffa22d4f33cdd8921422 to your computer and use it in GitHub Desktop.
Save rust-play/4a9bafd8f322ffa22d4f33cdd8921422 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#![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