Here's the Playground Link.
I cannot properly remove that .unwrap()
.
I have a JSON
body:
{
"currency": "dolar",
"quantity": "50"
}
quantity
is a String
because other languages have problems with large integer primitives (JS
), so here's my struct
currently:
#[derive(Deserialize)]
pub struct Amount {
pub currency: String,
pub quantity: String,
}
However, I wanted to change quantity
to be i128
:
#[derive(Deserialize)]
pub struct Amount {
pub currency: String,
pub quantity: i128,
}
Now I "just" needed to hack the deserialization and convert quantity
into i128
.
I found this on the internet: Variant attributes · Serde.
#[serde(deserialize_with = "path")]
Where "path" is a path to a function, I can pass a custom deserializer function to that field, so I did it.
#[derive(Deserialize)]
pub struct Amount {
pub currency: String,
#[serde(deserialize_with = "deserialize_string_into_i128")]
pub quantity: i128,
}
// NOTE: `D::Error` is `serde_json::Error` because I'm using `serde_json`.
pub fn deserialize_string_into_i128<'de, D>(deserializer: D) -> Result<i128, D::Error>
where
D: Deserializer<'de>,
{
let number = String::deserialize(deserializer)?;
let number = number.parse::<i128>().unwrap(); // HOW DO I REMOVE THIS UNWRAP?
Ok(number)
}
I ran into a problem, the String
method .parse::<i128>()
is fallible.
There is no way to return std::num::ParseIntError
, the function returns Result<128, D::Error>
.
I can't remove that .unwrap()
and treat the error.
Is there other way to do this?