Parsear y Serializar
En esta página
Schema.parse(mapa) recibe un mapa literal #{} e intenta construir una
instancia validada. El retorno es siempre un Result<Schema, str>: Result::Ok
con la instancia en caso de éxito, o Result::Err con un mensaje descriptivo
cuando algún campo está ausente o tiene el tipo incorrecto. Consume el resultado
con match, unwrap, unwrap_or, is_ok o is_err.
Point.parse con mapa completo devuelve Ok; mapa incompleto devuelve Err.
// Feature: schema validation — `Schema.parse(map)` returns Result<Schema, str>
// Syntax: pass a map to `parse`; on success you get `Result::Ok(instance)`,
// on failure `Result::Err(message)`. Use `match`, `unwrap`, or
// `is_ok` / `is_err` to consume the result idiomatically.
// When to use: validating untrusted input — HTTP bodies, CLI args,
// JSON payloads, file deserialization.
schema Point {
x: int,
y: int,
}
// Pattern-match the Result — the most idiomatic shape.
match Point.parse(#{x: 10, y: 20}) {
Result::Ok(p) => {
print(p.x)
print(p.y)
},
Result::Err(e) => print("error: {e}"),
}
// expected:
// 10
// 20
// Missing field → Err. The exact message is implementation-defined,
// but the variant is reliable.
match Point.parse(#{x: 10}) {
Result::Ok(_) => print("?"),
Result::Err(_) => print("validation failed"),
}
// expected: validation failed
El camino inverso es instancia.to_map(), que serializa todos los campos de
vuelta a un mapa — listo para enviar por la red, guardar en un archivo o
codificar como JSON. Junto con parse, forma el ciclo completo de validación
y serialización:
Rect.to_map() accede a los campos por el mapa; Point.to_map() + json.encode cierra el ciclo.
// Feature: schema serialization — `instance.to_map()` round-trips back to a map
// Syntax: any parsed schema instance has a `.to_map()` method.
// When to use: re-encoding to JSON, sending over the network,
// merging with other maps, structured logging.
use std::json
schema Rect {
width: int,
height: int,
}
match Rect.parse(#{width: 5, height: 3}) {
Result::Ok(r) => {
let m = r.to_map()
print(m["width"])
print(m["height"])
},
Result::Err(e) => print("error: {e}"),
}
// expected:
// 5
// 3
// Round-trip: parse → to_map → encode as JSON.
schema Point {
x: int,
y: int,
}
match Point.parse(#{x: 1, y: 2}) {
Result::Ok(p) => print(json.encode(p.to_map())),
Result::Err(e) => print("error: {e}"),
}
// expected: {"x":1,"y":2} (key order may vary)
Desafío
Crea un schema Email { address: str } e intenta parsear un mapa vacío #{}.
Imprime el mensaje de error recibido. Luego parsea un mapa válido, conviértelo
con to_map() y verifica que m["address"] devuelve el valor original.
Consulta también