2019-07-06 20:42:14 +00:00
|
|
|
# serde
|
|
|
|
|
|
|
|
[Serde](https://serde.rs/) is **rust** create used to _serialize_ and _deserialize_ stuff.
|
|
|
|
|
|
|
|
For example, this can be used to deserialize toml into a dedicated struct.
|
|
|
|
|
|
|
|
|
|
|
|
## Example, with toml
|
|
|
|
|
|
|
|
Here is how serde after version 1.0 (included) should be used with serialize/deserialize mechanisms.
|
|
|
|
|
2019-07-06 20:46:59 +00:00
|
|
|
**Be careful, there is breaking changes before version 1.0 and you can find confusing docs.**
|
2019-07-06 20:42:14 +00:00
|
|
|
|
|
|
|
### `main.rs` file
|
|
|
|
|
|
|
|
```rust
|
|
|
|
// crates
|
|
|
|
extern crate toml;
|
|
|
|
extern crate serde;
|
|
|
|
|
|
|
|
// uses
|
|
|
|
use serde::Deserialize;
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct Config {
|
|
|
|
name: String,
|
|
|
|
url: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let content = r#"name = "example"
|
|
|
|
url = "https://example.com""#;
|
|
|
|
|
|
|
|
let conf: Config = toml::from_str(content).unwrap();
|
|
|
|
|
|
|
|
println!("name: {}, url: {}", conf.name, conf.url)
|
|
|
|
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
### `Cargo.toml` file
|
|
|
|
|
|
|
|
```toml
|
|
|
|
[package]
|
|
|
|
name = "safiste"
|
|
|
|
version = "0.1.0"
|
|
|
|
authors = ["El Famoso Safiste"]
|
|
|
|
edition = "2018"
|
|
|
|
|
|
|
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
|
|
|
|
|
|
|
[dependencies]
|
|
|
|
serde = { version = "1.0.94", features = ["derive"] }
|
|
|
|
toml = "0.5.1"
|
|
|
|
```
|
|
|
|
|
|
|
|
### Output
|
|
|
|
|
|
|
|
```txt
|
|
|
|
name: example, url: https://example.com
|
|
|
|
```
|