Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created April 5, 2018 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/6fb51daf3a62d898769fc9184dc9ecd3 to your computer and use it in GitHub Desktop.
Save rust-play/6fb51daf3a62d898769fc9184dc9ecd3 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
// Trait to be delegated
trait Work {
fn do_work(&self) -> u64;
}
// Delegate trait, this would be in the std
// `Trait` refers to the trait we would delegate to
// We could imagine a variant of Delegate that would not accept a Trait
// parameter and stand for delegation of inherent impl.
trait Delegate<Trait: ?Sized> {
// The type to which we will delegate
type Inner;
fn inner(&self) -> &Self::Inner;
fn inner_mut(&mut self) -> &mut Self::Inner;
fn into_inner(self) -> Self::Inner;
fn from_inner(delegate: Self::Inner) -> Self;
}
// Struct to which we will delegate: will stand for our Inner type
struct Worker {
x: u64,
y: u64,
}
// Implementation of our target trait
impl Work for Worker {
fn do_work(&self) -> u64 {
self.x + self.y
}
}
// Struct that will delegate its Work implementation
struct Boss {
worker: Worker,
}
// Declare that we delegate our Work implementation
impl Delegate<Work> for Boss {
type Inner = Worker;
fn inner(&self) -> &Self::Inner {
&self.worker
}
fn inner_mut(&mut self) -> &mut Self::Inner {
&mut self.worker
}
fn into_inner(self) -> Self::Inner {
self.worker
}
fn from_inner(delegate: Self::Inner) -> Self {
Boss { worker: delegate }
}
}
// This would be generated by the compiler
impl<T: Work, U: Delegate<Work, Inner = T>> Work for U {
fn do_work(&self) -> u64 {
self.inner().do_work()
}
}
fn main() {
let boss = Boss {
worker: Worker { x: 12, y: 30 },
};
println!("Here are my results: {}", boss.do_work());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment