use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct Config {
host: String,
port: u16,
#[serde(default)]
debug: bool,
}
fn main() -> Result<(), serde_json::Error> {
let json = r#"{"host": "localhost", "port": 8080}"#;
let config: Config = serde_json::from_str(json)?;
println!("{:?}", config);
Ok(())
}
Serde is Rust's serialization framework, supporting JSON, YAML, TOML, MessagePack, and more through format-specific crates. With #[derive(Serialize, Deserialize)], your structs automatically convert to and from these formats. Serde is extremely fast because it generates specialized code at compile time and can borrow from the input (&str fields) without copying. I use serde_json for APIs, serde_yaml for config files, and bincode for binary protocols. The #[serde(rename = "...")] attribute maps Rust field names to external formats. For custom serialization, you can implement the traits manually. The ecosystem is mature, well-documented, and integrates with async I/O seamlessly. It's essential for any networked Rust application.
Related snips
struct Config<'a> {
name: &'a str,
value: &'a str,
}
fn parse_config(line: &str) -> Config {
Lifetime annotations for flexible borrowing in structs
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
use tracing::{info, instrument};
#[instrument]
fn process_request(user_id: u64) {
info!(user_id, "Processing request");
// Work happens here
tracing for structured logging and distributed tracing
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
Channels (mpsc) for message passing between threads
use clap::Parser;
#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Args {
#[arg(short, long)]
clap for CLI argument parsing with derive macros
macro_rules! create_function {
($func_name:ident) => {
fn $func_name() {
println!("Called {}", stringify!($func_name));
}
};
Declarative macros (macro_rules!) for code generation
Share this code
Here's the card — post it anywhere.