typestar

Estructuras anidadas en Rust

Structs dentro de vectores dentro de structs — serde sigue el árbol completo.

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct Tour {
    slug: String,
    sections: Vec<Section>,
}

#[derive(Debug, Serialize, Deserialize)]
struct Section {
    title: String,
    steps: Vec<String>,
}

fn main() -> Result<(), serde_json::Error> {
    let tour = Tour {
        slug: "traits".to_string(),
        sections: vec![Section {
            title: "Trait objects".to_string(),
            steps: vec!["rs_trait_objects.rs".to_string()],
        }],
    };
    println!("{}", serde_json::to_string_pretty(&tour)?);
    Ok(())
}

Cómo funciona

  1. Cualquier campo cuyo tipo derive los traits simplemente funciona.
  2. Vec<T> se vuelve un arreglo JSON de objetos.
  3. to_string_pretty es la forma legible.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
25
Caracteres a escribir
499
Tokens
134
Ritmo de tres estrellas
105 tpm

Al ritmo de tres estrellas de 105 tokens por minuto, este intento toma unos 77 segundos.

Escribe este fragmento

Paso 1 de 2 en Formas; paso 7 de 11 en Serde y JSON.

← Anterior Siguiente →