Rust

Serde & Serialization

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

20 câu hỏi phỏng vấn·
Mid-Level
1

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

Câu trả lời

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?

Câu trả lời

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?

Câu trả lời

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 câu hỏi phỏng vấn

Nắm vững Rust cho lần phỏng vấn tiếp theo

Truy cập tất cả câu hỏi, flashcards, bài kiểm tra kỹ thuật, bài tập code review và mô phỏng phỏng vấn.

Bắt đầu miễn phí