# getter **Repository Path**: itao007/getter ## Basic Information - **Project Name**: getter - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-12-15 - **Last Updated**: 2025-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## 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]`属性,则生成公有方法 ## 示例 源代码 ```rust #[derive(Debug, Getter)] struct GetterExample { #[get(default = 1)] age: Option, name: String, #[get(default = "tom")] nick_name: Option, #[get(pri)] counter: Option, #[get(skip)] skip: bool, protocol: Protocol, protocol_option: Option, } #[derive(Debug, Clone, Copy)] pub enum Protocol { Mysql, Postgres, Sqlite, } impl Default for Protocol { fn default() -> Self { Protocol::Mysql } } ``` 宏展开后的代码 ```rust 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 { &self.protocol_option } } ```