I am interested in making a variable not automatically serialized (e.g., by Serde) with the use of a keyword like Java's transient
, but in Rust. I need this to store passwords. Of course, I could manually clear the data upon serialization to the disk, but I would like to know if there are better, more automatic, options.
Serde. Serde, the incumbent serialization/deserialization library, is elegant, flexible, fast to run, and slow to compile.
transient variable in Java is a variable whose value is not serialized during Serialization and which is initialized by its default value during de-serialization, for example for object transient variable it would be null.
The main difference between the two ( static versus transient ) is that static variables exist only once per transaction, but transient variables can exist many times. In other words, static variables have a global scope, while transient variables have a local scope.
Transient in Java is used to indicate that a field should not be part of the serialization process. The modifier Transient can be applied to member variables of a class to turn off serialization on these member variables. Every field that is marked as transient will not be serialized.
You can use the #[serde(skip)]
attribute:
use serde::{Deserialize, Serialize}; // 1.0.88
#[derive(Deserialize, Serialize)]
struct MyStruct {
field1: i32, // this will be (de)serialized
#[serde(skip)]
field2: i32, // this will be skipped
}
If the type needs to be deserialized, it's a good idea to accompany a #[serde(skip)]
with a #[serde(default)]
(or a #[serde(default = "fn_name")]
) attribute. Serde deserializes skipped fields as if a #[serde(default)]
was implicitly added, but it's clearer to someone reading your code if you make it explicit where this value will come from.
See:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With