0Pricing
Learn Rust Coding · Lección

JSON y estado

Estado compartido y serialización

JSON y estado es una lección gratuita de Learn Rust Coding en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Learn Rust Coding, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Learn Rust Coding incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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 Serialize types in Json to respond
  • Define a Clone state struct, often wrapping Arc
  • Attach it with with_state, read it with State
  • Use Arc<Mutex> for mutable shared data and FromRef for substates

Next: middleware with tower layers.

Preguntas frecuentes

¿La lección «JSON y estado» es gratis?

Sí — el texto completo de «JSON y estado» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Learn Rust Coding, actualiza a CoddyKit PRO. El curso de Learn Rust Coding incluye 4 lecciones en total.

¿Qué aprenderé en «JSON y estado»?

Estado compartido y serialización Practicas Learn Rust Coding con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Learn Rust Coding?

No se requiere experiencia previa. Learn Rust Coding en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.

¿Cuánto tiempo toma la lección «JSON y estado»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Learn Rust Coding?

Sí. Cada lección de Learn Rust Coding incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Enrutamiento con Axum
  2. Extractores
  3. JSON y estado
  4. Middleware
← Volver a Learn Rust Coding