dtolnay / serde-yaml

Strongly typed YAML library for Rust
Apache License 2.0
964 stars 164 forks source link

how to reject incorrect numeric type for `: String`? #349

Open asottile opened 1 year ago

asottile commented 1 year ago

I'm relatively new to serde so apologies if this is something obvious I missed from the docs.

here's a self-contained example:

#[derive(serde::Deserialize, Debug)]
struct T {
    pub(crate) s: String,
}

fn main() {
    if let Ok(t) = serde_yaml::from_str::<T>("s: 5\n") {
        println!("t.s: {}", t.s);
    } else {
        println!("error!");
    }
}
[package]
name = "y"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde = { version = "1.0.152", features = ["derive"] }
serde_yaml = "0.9.16"

the execution of this

$ cargo run main
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/y main`
t.s: 5

I expect an error however


in python for example, the parsing of x: 5 is {'x': 5} -- that is, 5 is an integer literal in yaml

my expectation was that s: String would reject an integer when deserializing, but it seems to silently convert the value to a String