JSON et état
État partagé et sérialisation
JSON et état est une leçon Learn Rust Coding gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Learn Rust Coding, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Learn Rust Coding comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
Returning JSON
Axum makes JSON responses easy. Wrap any Serialize type in Json and it sets the content type and serializes the body.
use axum::Json;
use serde::Serialize;
#[derive(Serialize)]
struct User { id: u32, name: String }
async fn get_user() -> Json<User> {
Json(User { id: 1, name: "Alice".into() })
}Serializing collections
A Vec of serializable items becomes a JSON array. No extra work needed.
use axum::Json;
use serde::Serialize;
#[derive(Serialize)]
struct Item { id: u32 }
async fn list() -> Json<Vec<Item>> {
Json(vec![Item { id: 1 }, Item { id: 2 }])
}Modeling JSON in plain Rust
JSON serialization is just turning a struct into a string. With serde_json you call to_string. Here is the idea using a manual format.
struct User { id: u32, name: String }
fn to_json(u: &User) -> String {
format!("{{\"id\":{},\"name\":\"{}\"}}", u.id, u.name)
}
fn main() {
let u = User { id: 1, name: "Alice".to_string() };
println!("{}", to_json(&u));
}What is shared state?
Shared state is data every handler can access, such as a database pool or config. Axum threads it through with the State extractor.
Defining app state
Define a struct holding your shared data. Often it wraps an Arc so cloning is cheap.
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
name: Arc<String>,
}Attaching state to the router
Pass the state to with_state. Axum stores it and provides it to handlers that ask for it.
use axum::{Router, routing::get};
async fn handler() -> &'static str { "ok" }
fn app(state: AppState) -> Router {
Router::new().route("/", get(handler)).with_state(state)
}Reading state in a handler
Add a State parameter to receive a clone of your state inside the handler.
use axum::extract::State;
async fn handler(State(state): State<AppState>) -> String {
state.name.to_string()
}Mutable shared state
For data that changes, guard it with a lock such as Mutex behind an Arc. This allows safe concurrent mutation.
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct Counter {
count: Arc<Mutex<u32>>,
}Mutating behind a Mutex
Lock the mutex, modify the value, then the guard drops. This runnable example mirrors the increment a handler would perform.
use std::sync::{Arc, Mutex};
fn main() {
let count = Arc::new(Mutex::new(0u32));
{
let mut guard = count.lock().unwrap();
*guard += 1;
}
println!("count = {}", *count.lock().unwrap());
}Accepting and echoing JSON
Combine input and output JSON: deserialize the body, transform it, and return JSON. A common create-then-respond pattern.
use axum::Json;
use serde::{Serialize, Deserialize};
#[derive(Deserialize)]
struct Input { name: String }
#[derive(Serialize)]
struct Output { greeting: String }
async fn greet(Json(i): Json<Input>) -> Json<Output> {
Json(Output { greeting: format!("Hi {}", i.name) })
}Substate with FromRef
When state holds several pieces, derive FromRef so handlers can extract just the part they need.
use axum::extract::FromRef;
#[derive(Clone)]
struct Pool;
#[derive(Clone, FromRef)]
struct AppState {
pool: Pool,
}Quick Check
Test your understanding of JSON and state.
Recap
You learned JSON and shared state:
- Wrap
Serializetypes inJsonto respond - Define a
Clonestate struct, often wrappingArc - Attach it with
with_state, read it withState - Use
Arc<Mutex>for mutable shared data andFromReffor substates
Next: middleware with tower layers.
Questions Fréquemment Posées
La leçon « JSON et état » est-elle gratuite ?
Oui — le texte complet de « JSON et état » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Learn Rust Coding, passe à CoddyKit PRO. Le cours Learn Rust Coding comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « JSON et état » ?
État partagé et sérialisation Tu pratiques Learn Rust Coding avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Learn Rust Coding ?
Aucune expérience préalable n'est requise. Learn Rust Coding sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.
Combien de temps prend la leçon « JSON et état » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Learn Rust Coding ?
Oui. Chaque leçon Learn Rust Coding inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Routage avec Axum
- Extracteurs
- JSON et état
- Intergiciel