Hi,
I'm creating a library to handle money by using BigInts
and now I'm trying to store those values in a database. I'm thinking of serializing the data to a JSON string and save it as text and then read it from the database when I need it.
The serializing works but I can't make the deserializing work as it is giving me the following error:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements
--> src\serialization.rs:18:5
|
18 | currency: Currency,
| ^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'de` as defined on the impl at 14:35...
--> src\serialization.rs:14:35
From what I can understand, the problem is about using a static
lifetime in the Currency
struct that outlives the de
lifetime. I'm using a static str
here because it allows me to use the Copy
trait so I can just copy the variable everywhere.
What should I change to make it work?
Cargo.toml
[dependencies]
num = { version = "0.3.1", features = ["serde"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
main.rs
use num::bigint::{BigInt};
use serde::{Deserialize, Serialize};
#[derive(Debug, Eq, PartialEq, Clone, Copy, Serialize, Deserialize)]
pub struct Currency {
name: &'static str,
symbol: &'static str,
separator: &'static str,
decimal: &'static str,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Money {
amount: BigInt,
precision: u32,
currency: Currency,
}
pub fn main() {
let usd = Currency {
name: "USD",
symbol: "$",
separator: ",",
decimal: ".",
};
let money_1 = Money {
amount: BigInt::from(100),
precision: 0,
currency: usd,
};
let money_2 = Money {
amount: BigInt::from(200),
precision: 0,
currency: usd,
};
let json_1 = serde_json::to_string(&money_1).unwrap();
println!("{:?}", json_1);
let json_2 = serde_json::to_string(&money_2).unwrap();
println!("{:?}", json_2);
}