Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of Java's transient in Serde?

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.

like image 953
Thomas Braun Avatar asked Apr 03 '19 23:04

Thomas Braun


People also ask

Is Serde fast?

Serde. Serde, the incumbent serialization/deserialization library, is elegant, flexible, fast to run, and slow to compile.

What is the value of transient variable while Deserializing?

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.

What is difference between transient and static in serialization?

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.

Is transient in Java modifier?

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.


1 Answers

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:

  • List of all serde field attributes
  • All serde attributes
like image 113
Peter Hall Avatar answered Dec 14 '22 19:12

Peter Hall