Rust

Serde & Serialization

serde traits, derive macros, JSON/YAML/TOML, custom (de)serialization, lifetimes with Cow, performance

20 面接問題·
Mid-Level
1

What is the main role of the serde crate in Rust?

回答

Serde is a generic serialization and deserialization framework for Rust. Its name comes from "SERialize DEserialize". It allows converting Rust data structures to and from various data formats (JSON, YAML, TOML, etc.) in an efficient and type-safe manner. Serde uses Rust's trait system to provide a zero-cost abstraction.

2

What is the correct syntax to enable automatic serialization on a struct with serde?

回答

The #[derive(Serialize, Deserialize)] attribute automatically generates the implementations of the Serialize and Deserialize traits for a struct. This procedural macro analyzes the field structure and generates the necessary code at compile time. You need to import the traits from serde with use serde::{Serialize, Deserialize}.

3

Which function should be used to convert a Rust struct to a JSON string with serde_json?

回答

The serde_json::to_string() function converts a value implementing Serialize into a JSON string. It returns a Result<String, Error> because serialization can fail in certain cases. For formatted output with indentation, use serde_json::to_string_pretty(). To write directly to a Writer, use serde_json::to_writer().

4

How to deserialize a JSON string into a Rust struct with serde_json?

5

Which serde attribute should be used to rename a field during serialization?

+17 面接問題

次の面接に向けてRustをマスター

すべての問題、flashcards、技術テスト、コードレビュー演習、面接シミュレーターにアクセス。

無料で始める