目录
一、需求说明
二、知识点
serde
一、需求说明
需求描述:用Rust写一个人员基本信息的实体类, 包括编号、姓名、描述、性别、备注、照片、简历等,加上3条测试数据,输出为json。
cargo add serde serde = { version = "1.0.201", features = ["derive"] }
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct Person {
id: u32,
code: String,
name: String,
description: String,
gender: Gender,
remark: String,
photo: String,
resume: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum Gender {
Male,
Female,
}
impl Person {
pub fn new(id: u32, code: &str,name: &str, description: &str, gender: Gender, remark: &str, photo: &str, resume: &str) -> Self {
Person {
id,
code: code.to_string(),
name: name.to_string(),
description: description.to_string(),
gender,
remark: remark.to_string(),
photo: photo.to_string(),
resume: resume.to_string(),
}
}
pub fn get_id(&self) -> u32 {
self.id
}
pub fn get_code(&self) -> &String {
&self.code
}
pub fn get_name(&self) -> &String {
&self.name
}
pub fn get_description(&self) -> &String {
&self.description
}
pub fn get_gender(&self) -> &Gender {
&self.gender
}
pub fn get_remark(&self) -> &String {
&self.remark
}
pub fn get_photo(&self) -> &String {
&self.photo
}
pub fn get_resume(&self) -> &String {
&self.resume
}
}
fn main() {
let person1 = Person::new(1,"zhangsan", "张三", "软件工程师", Gender::Male, "负责开发和维护", "https://127.0.0.1:8080/ierp/images/photo1.jpg", "https://127.0.0.1:8080/ierp/resumes/resume1.pdf");
let person2 = Person::new(2,"lisi", "李四", "产品经理", Gender::Female, "负责产品规划和管理", "https://127.0.0.1:8080/ierp/images/photo2.jpg", "https://127.0.0.1:8080/ierp/resumes/resume2.pdf");
let person3 = Person::new(3,"wangwu", "王五", "设计师", Gender::Male, "负责界面设计和用户体验", "https://127.0.0.1:8080/ierp/images/photo3.jpg", "https://127.0.0.1:8080/ierp/resumes/resume3.pdf");
let persons = vec![person1, person2, person3];
let json = serde_json::to_string(&persons).unwrap();
println!("{}", json);
}
二、知识点
serde
serde - RustSerdehttps://docs.rs/serde/1.0.202/serde/
Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.
Serde是一个用于高效和通用地序列化和反序列化Rust数据结构的框架。
serde即是rust的“NetonSoftJson”