getter

Crates.iogetter
lib.rsgetter
version0.2.0
created_at2025-12-17 02:32:03.962004+00
updated_at2025-12-19 04:04:37.010522+00
description生成get方法
homepage
repositoryhttps://gitee.com/itao007/getter.git
max_upload_size
id1989195
size19,092
itao (bj-sjt)

documentation

https://docs.rs/getter

README

通过派生宏#[derive(Getter)]为结构体字段生成get方法,字段可附加#[get]属性

  • 结构体只能是named struct
  • 方法名为字段名

get属性可选值

  • skip:bool类型,为true时,不为该字段生成get方法
  • pri: bool类型,为true时,为该字段生成私有方法
  • default: 表达式,字段为非[Option]类型或[Option]泛型不是进本数据类型和[String]类型会忽略该字段

说明

字段为非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 }
}
Commit count: 0

cargo fmt