通过派生宏#[derive(Getter)]为结构体字段生成get方法,字段可附加#[get]属性
- 结构体只能是named struct
- 方法名为字段名
get属性可选值
- skip:bool类型,为true时,不为该字段生成
get方法
- pri: bool类型,为true时,为该字段生成私有方法
- default: 表达式,字段为非Option类型会忽略该字段
说明
字段为非Option类型
- 字段类型为
基本数据类型则,方法返回基本数据类型
- 字段类型为
String类型则,方法返回&str类型
- 字段类型为
其它类型则,方法返回其它类型则的引用
字段为Option类型
- 字段包裹类型为
基本数据类型,则,方法返回基本数据类型
- 字段包裹类型为
String类型,则,方法返回&str类型
- 字段包裹类型为
其它类型,则不生成该字段的get方法
字段上没有#[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 }
}