#getter-setter #getter #setter

shorthand

一个过程宏,用于为struct结构体生成getter和setter

2个版本

0.1.1 2020年2月1日
0.1.0 2020年1月26日

#25 in #setter

Download history 475/week @ 2024-03-13 219/week @ 2024-03-20 208/week @ 2024-03-27 228/week @ 2024-04-03 151/week @ 2024-04-10 148/week @ 2024-04-17 118/week @ 2024-04-24 100/week @ 2024-05-01 81/week @ 2024-05-08 113/week @ 2024-05-15 103/week @ 2024-05-22 122/week @ 2024-05-29 116/week @ 2024-06-05 74/week @ 2024-06-12 135/week @ 2024-06-19 114/week @ 2024-06-26

455 每月下载量
用于 6 个crate(2 个直接使用)

MIT/Apache

110KB
2K SLoC

shorthand

Crates.io: shorthand Documentation Build Status

shorthand 被定义为 一种快速书写系统,这正是这个库的目的;移除编写自己的库时遇到的繁琐样板代码。

这个库能做什么?

它通过为struct结构体的字段生成getter和setter,使Rust编程变得更加方便。

use shorthand::ShortHand;

#[derive(ShortHand, Default)]
pub struct Example {
    number: usize,
    data: String,
}

let mut example = Example::default();

assert_eq!(example.number(), 0);
example.set_number(1);
assert_eq!(example.number(), 1);

assert_eq!(example.data(), &"".to_string());
example.set_data("hi".to_string());
assert_eq!(example.data(), &"hi".to_string());

否则,您将不得不手动编写这些代码

pub struct Example {
    number: usize,
    data: String,
}

#[allow(dead_code)]
impl Example {
    #[inline(always)]
    pub fn number(&self) -> usize { self.number }

    #[inline(always)]
    pub fn set_number(&mut self, value: usize) -> &mut Self {
        self.number = value;
        self
    }

    #[inline(always)]
    pub fn data(&self) -> &String { &self.data }

    #[inline(always)]
    pub fn set_data(&mut self, value: String) -> &mut Self {
        self.data = value;
        self
    }
}

如何开始?

只需将此库添加到您的 [dependencies] 中的 Cargo.toml

[dependencies]
shorthand = "0.1.0"

然后您可以为任何结构体推导出 ShortHand

use shorthand::ShortHand;

#[derive(ShortHand)]
struct Example {
    field: usize,
}

您可以在此处找到文档。

功能请求和错误报告

请随时提问或报告错误 此处。没有愚蠢的问题。

此库应该尽可能方便,因此请不要犹豫请求一个功能。

参考

此库受到了以下crate的启发

依赖

~1.5MB
~35K SLoC