use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct InstitutionObject {
// 雪花id
#[serde(default)]
pub id: String,
// 核酸结果(0-阴性 1-阳性 2-无效)
#[serde(default)]
pub result_type: i32,
// 检测机构id
#[serde(default)]
pub institution_id: String,
// 核酸登记id
#[serde(default)]
pub registe_id: String,
// 创建时间
#[serde(default)]
pub create_time: String,
}
#[allow(dead_code)]
impl InstitutionObject {
pub fn new(id: String, result_type: i32, institution_id: String, registe_id: String, create_time: String) -> InstitutionObject {
InstitutionObject {
id,
result_type,
institution_id,
registe_id,
create_time,
}
}
pub fn tets(id: String, result_type: i32, institution_id: String) -> InstitutionObject {
InstitutionObject {
id: id,
result_type: result_type,
institution_id: institution_id,
}
}
}
This code can't be compiled. If I can't ignore it, I have to declare another struct
I don't want to declare a struct again. In fact, I can create multiple view objects or business object according to requirements by creating an instance
I didn't find similar instructions on this official website struct
There are two things you can do:
- Set the type of certain fields, which are optional as
Option<String>
for create_time
.
- Create a top-level enum, with different variants for different "things"
enum Institute {
Regular(RegularInstitute),
Unregistered(UnregisteredInstitute)
}
Use the former if you have an object which may exist in various "states" - such as initially all institutes are unregisterered, then they get registered.
Use the latter is un-registered institutes and registered institutes both exist and are distinct.
Can't you make the fields optional by using the Option
type?
Do you mean i can set the none property for it, In case of no value
thanks
#[serde(default)]
pub registe_id: Option<String>,
// 创建时间
#[serde(default)]
pub create_time: Option<String>,
pub fn tets(id: String, result_type: i32, institution_id: String) -> InstitutionObject {
InstitutionObject {
id: id,
result_type: result_type,
institution_id: institution_id,
registe_id: None,
create_time: None,
}
}
#[cfg(test)]
mod tests {
use std::{cell::RefCell, rc::Rc};
use super::*;
#[test]
fn test_ingore_param() {
let a = RefCell::new(Rc::new(InstitutionObject::tets(String::from("4"), 6, String::from("7"))));
println!("{:?}", a);
}
}
When I print the field, I look at it and return None
, but I accept it at the front end. I don't want this field to appear. it can be ignored during serialization
Maybe a top-level enum is a good choice. I'll try it later. Thank you
You can skip serialization in Serde using field attributes like this:
#[serde(skip_serializing_if = "Option::is_none")]