How do I tell you the flexibility of the model when I read toml?

Asked 2 years ago, Updated 2 years ago, 63 views

I heard that a structure is necessary to load toml in trust, but how can I tell you about the flexibility of the model?

use service_derive::Deserialize;

# [derive (Deserialize)]
US>structure User {
    user:string<-- I want to be able to do numbers as well
}
US>fnmain(){
    let user: User=toml::from_str(r#"
    user=1234
    US>"#).unwrap()
    );
}

rust

2022-09-30 16:19

1 Answers

The TOML specification interprets it as an integer type, so it should be enclosed in ".

let user:User=toml::from_str(r#"user="1234""#).unwrap();

Or you can use enum to write as follows:

use service::Deserialize;

# [derive (Deserialize, Debug)]
#[serde(untagged)]
enum User {
    ByName {user:String},
    ByNumber {user:i32},
}

US>fnmain(){
    let user1: User=toml::from_str(r#"user=1234"#).unwrap();
    let user2:User=toml::from_str(r#"user="foo""#).unwrap();
    println!("{:?}, {:?}", user1, user2)
}
ByNumber {user:1234}, ByName {user:"foo"}

Enum presents Serde


2022-09-30 16:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.