JSON e estado
Estado compartilhado e serialização
JSON e estado é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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.
Perguntas Frequentes
A aula “JSON e estado” é grátis?
Sim — o texto completo de “JSON e estado” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 4 aulas no total.
O que vou aprender em “JSON e estado”?
Estado compartilhado e serialização Você pratica Learn Rust Coding com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Learn Rust Coding?
Nenhuma experiência prévia é necessária. Learn Rust Coding no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “JSON e estado”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Learn Rust Coding?
Sim. Cada aula de Learn Rust Coding inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Roteamento com Axum
- Extratores
- JSON e estado
- Middleware