Deserializing TOML into vector of enum with values

前端 未结 1 1173
执念已碎
执念已碎 2021-01-13 02:18

I\'m trying to read a TOML file to create a struct that contains a vector of enums with associated values. Here\'s the sample code:

extern crate serde;
#[mac         


        
相关标签:
1条回答
  • 2021-01-13 03:03

    Serde has lots of options for serializing enums. One that works for your case:

    use serde::{Deserialize, Serialize}; // 1.0.117
    use toml; // 0.5.7
    
    #[derive(Debug, Serialize, Deserialize, PartialEq)]
    #[serde(tag = "type", content = "args")]
    enum Actions {
        Wait(usize),
        Move { x: usize, y: usize },
    }
    
    fn main() {
        let a_wait = Actions::Wait(5);
        println!("{}", toml::to_string(&a_wait).unwrap());
    
        let a_move = Actions::Move { x: 1, y: 1 };
        println!("{}", toml::to_string(&a_move).unwrap());
    }
    
    type = "Wait"
    args = 5
    
    type = "Move"
    
    [args]
    x = 1
    y = 1
    
    0 讨论(0)
提交回复
热议问题