0Pricing
Learn Rust Coding · درس

JSON والحالة

الحالة المشتركة والتسلسل

JSON والحالة درس مجاني في Learn Rust Coding على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Learn Rust Coding، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Learn Rust Coding 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

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.

الأسئلة الشائعة

هل درس «JSON والحالة» مجاني؟

نعم — نص درس «JSON والحالة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Learn Rust Coding، انتقل إلى CoddyKit PRO. تتضمن دورة Learn Rust Coding 4 دروس في المجموع.

ماذا ستتعلم في «JSON والحالة»؟

الحالة المشتركة والتسلسل تتمرن على Learn Rust Coding مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Learn Rust Coding؟

لا تُشترط خبرة سابقة. Learn Rust Coding على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.

كم من الوقت يستغرق درس «JSON والحالة»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Learn Rust Coding هذا؟

نعم. كل درس في Learn Rust Coding يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. التوجيه في Axum
  2. المستخرِجات
  3. JSON والحالة
  4. البرمجيات الوسيطة
← العودة إلى Learn Rust Coding