Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid Serde needing the Default trait for a field that skips serialization?

Tags:

rust

serde

I have this struct that is created by deserializing with Serde and I want to have a field of type Url in it which is not deserialized:

#[derive(Deserialize, Debug)]
pub struct Flow {
    #[serde(skip_deserializing)]
    pub source: Url,
}

Playground

Serde complains about Url not satisfying the Default trait. I have tried with and without deriving Default. Is my only option for me to implement the Default trait for Url myself?

like image 985
Andrew Mackenzie Avatar asked Jan 24 '18 09:01

Andrew Mackenzie


People also ask

Is SerDe slow?

Serde is really designed to be fast, by allowing fully statically dispatched operations without runtime reflections so formats and types are decoupled at code but transparent to the optimization.

What is serialization and Deserialization in Rust?

Rustc has to serialize and deserialize various data during compilation. Specifically: "Crate metadata", mainly query outputs, are serialized in a binary format into rlib and rmeta files that are output when compiling a library crate, these are then deserialized by crates that depend on that library.

What is SerDe name?

SerDe is a short name for "Serializer and Deserializer." Hive uses SerDe (and FileFormat) to read and write table rows. HDFS files --> InputFileFormat --> <key, value> --> Deserializer --> Row object. Row object --> Serializer --> <key, value> --> OutputFileFormat --> HDFS files.


2 Answers

You can use #[serde(default = "path")] on the field to give a function with the signature fn() -> Url that should be called if the field is missing.

like image 200
oli_obk Avatar answered Sep 20 '22 10:09

oli_obk


It's also possible to implement Deserialize yourself and handle missing values appropriately.

like image 38
Zargony Avatar answered Sep 20 '22 10:09

Zargony