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 แบบทดสอบเทคนิค แบบฝึกหัด code review และตัวจำลองสัมภาษณ์

เริ่มใช้ฟรี