6次发布
0.0.6 | 2023年6月3日 |
---|---|
0.0.5 | 2023年5月29日 |
#1081 in 过程宏
54 每月下载量
32KB
727 代码行
auto-delegate
支持 无std
此库是在没有std crate的情况下创建的。
描述
自动委托允许您自动实现特性和将它们的处理委托给子成员。
用法
结构体
将 'delegate' 属性赋予要委托的特质,将 'Delegate' 赋予请求委托的结构体
示例1
use auto_delegate::{Delegate, delegate};
#[delegate]
trait Calc {
fn calc(&self, x1: usize, x2: usize) -> usize;
}
#[derive(Default)]
struct CalcAdd;
impl Calc for CalcAdd {
fn calc(&self, x1: usize, x2: usize) -> usize {
x1 + x2
}
}
#[derive(Delegate, Default)]
struct Parent {
#[to(Calc)]
child: CalcAdd
}
fn main() {
let parent = Parent::default();
assert_eq!(parent.calc(2, 3), 5);
}
示例2:多个特性和字段
use auto_delegate::*;
#[delegate]
trait Calc {
fn calc(&self, x1: usize, x2: usize) -> usize;
}
#[derive(Default)]
struct CalcAdd;
impl Calc for CalcAdd {
fn calc(&self, x1: usize, x2: usize) -> usize {
x1 + x2
}
}
#[delegate]
trait Movable {
fn move_to(&mut self, pos: (usize, usize));
fn pos(&self) -> (usize, usize);
}
#[delegate]
trait Resizable {
fn resize(&mut self, width: usize, height: usize);
fn size(&self) -> (usize, usize);
}
#[derive(Default)]
struct Transform2D {
pos: (usize, usize),
width: usize,
height: usize
}
impl Movable for Transform2D {
fn move_to(&mut self, pos: (usize, usize)) {
self.pos = pos;
}
fn pos(&self) -> (usize, usize) {
self.pos
}
}
impl Resizable for Transform2D {
fn resize(&mut self, width: usize, height: usize) {
self.width = width;
self.height = height;
}
fn size(&self) -> (usize, usize) {
(self.width, self.height)
}
}
#[derive(Default, Delegate)]
struct Parent<T: Default + Calc> {
#[to(Movable, Resizable)]
transform: Transform2D,
#[to(Calc)]
calculator: T
}
fn main() {
let mut parent = Parent::<CalcAdd>::default();
assert_eq!(parent.calc(3, 2), 5);
parent.move_to((10, 11));
assert_eq!(parent.pos(), (10, 11));
parent.resize(100, 120);
assert_eq!(parent.size(), (100, 120));
}
枚举
与结构体类似,枚举可以使用Delegate进行委托。
示例
use auto_delegate::{delegate, Delegate};
#[delegate]
trait Calc {
fn calc(&self, x1: usize, x2: usize) -> usize;
}
#[derive(Default)]
struct CalcAdd;
impl Calc for CalcAdd {
fn calc(&self, x1: usize, x2: usize) -> usize {
x1 + x2
}
}
#[derive(Default)]
struct CalcSub;
impl Calc for CalcSub {
fn calc(&self, x1: usize, x2: usize) -> usize {
x1 - x2
}
}
#[derive(Delegate)]
#[to(Calc)]
enum EnumCalc {
Add(CalcAdd),
Sub(CalcSub),
}
fn main() {
let c = EnumCalc::Add(CalcAdd::default());
assert_eq!(c.calc(3, 5), 8);
let c = EnumCalc::Sub(CalcSub::default());
assert_eq!(c.calc(3, 2), 1);
}
待办事项
- 支持自接收器(v0.0.8)
- 支持无接收器的方法(v0.1.0)
依赖项
~275–730KB
~17K SLoC