我正在尝试创建一个宏来生成一个可以从 postgres 数据库填充的结构。现在,由于数据库中有可以为空和不可为空的字段,我想在宏中以不同的方式处理它们。
输出应该是这样的结构:
#[derive(Debug, Default)]
pub struct MyStruct {
pub attrib_a: i64,
pub attrib_b: Option<i64>,
}
impl MyStruct {
pub fn get_row(&self, row: &postgres::rows::Row) -> MyStruct {
MyStruct {
// the non-nullable attrib_a, where I can for sure take the value out of the Option and assign it
attrib_a: match row.get::<_, Option<i64>>("attrib_a") {
Some(x) => x,
None => 0,
},
// here for the nullable attrib_b I just want to return the Option as is
attrib_b: row.get::<_, Option<i64>>("attrib_b"),
}
}
}
这是当前的宏代码:
macro_rules! make_table_struct {
($tname: stmt => $sname: ident; $($fname: ident: $ftype: ty),+) => {
#[derive(Debug, Clone, Default)]
pub struct $sname {
$(
pub $fname: $ftype,
)+
}
impl $sname
{
pub fn get_row(&self,row:&postgres::rows::Row)->$sname
{
$sname
{
//How do I know if I have an Option here or not and act then accordingly?
$(
$fname: row.get::<_,Option<$ftype>>(stringify!($fname)),
)+
}
}
}
}
}
宏调用:
make_table_struct! ("source_table_name" => MyStruct; attrib_a: i64, attrib_b: Option<i64>)