chancancode / Rust Delegate
Programming Languages
Labels
Projects that are alternatives of or similar to Rust Delegate
Method delegation with less boilerplate
This crate removes some boilerplate for structs that simply delegate some of their methods to one or more of their fields.
It gives you the delegate!
macro, which delegates method calls to selected expressions (usually inner fields).
Example:
A Stack data structure implemented using an inner Vec via delegation.
use delegate::delegate;
#[derive(Clone, Debug)]
struct Stack<T> {
inner: Vec<T>,
}
impl<T> Stack<T> {
pub fn new() -> Self<T> {
Self { inner: vec![] }
}
delegate! {
to self.inner {
pub fn is_empty(&self) -> bool;
pub fn push(&mut self, value: T);
pub fn pop(&mut self) -> Option<T>;
pub fn clear(&mut self);
#[call(len)]
pub fn size(&self) -> usize;
#[call(last)]
pub fn peek(&self) -> Option<&T>;
}
}
}
Features:
- Delegate to a method with a different name
struct Stack { inner: Vec<u32> }
impl Stack {
delegate! {
to self.inner {
#[call(push)]
pub fn add(&mut self, value: u32);
}
}
}
- Use an arbitrary inner field expression
struct Wrapper { inner: Rc<RefCell<Vec<u32>>> }
impl Wrapper {
delegate! {
to self.inner.deref().borrow_mut() {
pub fn push(&mut self, val: u32);
}
}
}
- Change the return type of the delegated method using a
From
impl or omit it altogether
struct Inner;
impl Inner {
pub fn method(&self, num: u32) -> u32 { num }
}
struct Wrapper { inner: Inner }
impl Wrapper {
delegate! {
to self.inner {
// calls method, converts result to u64
#[into]
pub fn method(&self, num: u32) -> u64;
// calls method, returns ()
#[call(method)]
pub fn method_noreturn(&self, num: u32);
}
}
}
- Delegate to multiple fields
struct MultiStack {
left: Vec<u32>,
right: Vec<u32>,
}
impl MultiStack {
delegate! {
to self.left {
/// Push an item to the top of the left stack
#[call(push)]
pub fn push_left(&mut self, value: u32);
}
to self.right {
/// Push an item to the top of the right stack
#[call(push)]
pub fn push_right(&mut self, value: u32);
}
}
}
- Delegation of generic methods
- Inserts
#[inline(always)]
automatically (unless you specify#[inline]
manually on the method)
License
Licensed under either of
- Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
Conduct
Please follow the Rust Code of Conduct. For escalation or moderation issues
please contact the crate author(s) listed in Cargo.toml
.