< 返回版块

1911860538 发表于 2024-01-31 14:23

use serde::{Deserialize, Serialize};

pub enum ColumnType {
    Integer(i64),
    String(String),
    Float(f64),
    Bool(bool),
}

impl Serialize for ColumnType {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: serde::Serializer,
    {
        match self {
            ColumnType::Integer(val) => val.serialize(serializer),
            ColumnType::String(val) => val.serialize(serializer),
            ColumnType::Float(val) => val.serialize(serializer),
            ColumnType::Bool(val) => val.serialize(serializer),
        }
    }
}


#[derive(Serialize, Deserialize)]
struct Filter<'a> {
    attribute_name: &'a str,
    operator: &'a str,
    value: ColumnType,
    value_type: &'a str,
}

fn main() {
    
}

Deserialize要怎么写,怎么避免引起'de生命周期

评论区

写评论
作者 1911860538 2024-02-01 11:02

谢谢

--
👇
liusen-adalab:

use std::borrow::Cow;

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, PartialEq, Debug)]
#[serde(untagged)]
pub enum ColumnType<'a> {
    Integer(i64),
    String(Cow<'a, str>),
    Float(f64),
    Bool(bool),
}

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Filter<'a> {
    attribute_name: &'a str,
    operator: &'a str,
    value: ColumnType<'a>,
    value_type: &'a str,
}

#[test]
fn main() {
    let filter1 = Filter {
        attribute_name: "age",
        operator: "eq",
        value: ColumnType::Integer(10),
        value_type: "int",
    };
    println!("{}", serde_json::to_string_pretty(&filter1).unwrap());

    let filter_str = r#"
        {
            "attribute_name": "age",
            "operator": "eq",
            "value": 10,
            "value_type": "int"
        }"#;

    let filter2: Filter = serde_json::from_str(filter_str).unwrap();

    assert_eq!(filter1, filter2);
}

liusen-adalab 2024-02-01 10:37
use std::borrow::Cow;

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, PartialEq, Debug)]
#[serde(untagged)]
pub enum ColumnType<'a> {
    Integer(i64),
    String(Cow<'a, str>),
    Float(f64),
    Bool(bool),
}

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Filter<'a> {
    attribute_name: &'a str,
    operator: &'a str,
    value: ColumnType<'a>,
    value_type: &'a str,
}

#[test]
fn main() {
    let filter1 = Filter {
        attribute_name: "age",
        operator: "eq",
        value: ColumnType::Integer(10),
        value_type: "int",
    };
    println!("{}", serde_json::to_string_pretty(&filter1).unwrap());

    let filter_str = r#"
        {
            "attribute_name": "age",
            "operator": "eq",
            "value": 10,
            "value_type": "int"
        }"#;

    let filter2: Filter = serde_json::from_str(filter_str).unwrap();

    assert_eq!(filter1, filter2);
}

1 共 2 条评论, 1 页