| Crates.io | getter |
| lib.rs | getter |
| version | 0.2.0 |
| created_at | 2025-12-17 02:32:03.962004+00 |
| updated_at | 2025-12-19 04:04:37.010522+00 |
| description | 生成get方法 |
| homepage | |
| repository | https://gitee.com/itao007/getter.git |
| max_upload_size | |
| id | 1989195 |
| size | 19,092 |
#[derive(Getter)]为结构体字段生成get方法,字段可附加#[get]属性
- 结构体只能是named struct
- 方法名为字段名
get属性可选值
get方法Option类型基本数据类型,则方法返回基本数据类型String类型,则方法返回&str类型其它类型则,则方法返回其它类型则的引用Option类型基本数据类型,则方法返回基本数据类型String类型,则方法返回&str类型其它类型,则方法返回Option类型字段上没有
#[get]属性,则生成公有方法
源代码
#[derive(Debug, Getter)]
struct GetterExample {
#[get(default = 1)]
age: Option<u8>,
name: String,
#[get(default = "tom")]
nick_name: Option<String>,
#[get(pri)]
counter: Option<u32>,
#[get(skip)]
skip: bool,
protocol: Protocol,
protocol_option: Option<Protocol>,
}
#[derive(Debug, Clone, Copy)]
pub enum Protocol {
Mysql,
Postgres,
Sqlite,
}
impl Default for Protocol {
fn default() -> Self {
Protocol::Mysql
}
}
宏展开后的代码
impl GetterExample {
#[inline(always)]
pub fn age(&self) -> u8 { self.age.unwrap_or(1) }
#[inline(always)]
pub fn name(&self) -> &str { &self.name }
#[inline(always)]
pub fn nick_name(&self) -> &str { &self.nick_name.as_deref().unwrap_or("tom") }
#[inline(always)]
fn counter(&self) -> u32 { self.counter.unwrap_or_default() }
#[inline(always)]
pub fn protocol(&self) -> &Protocol { &self.protocol }
#[inline(always)]
pub fn protocol_option(&self) -> &Option<Protocol> { &self.protocol_option }
}