Pular para o conteúdo

Parsear e Serializar

Nesta página

Schema.parse(mapa) recebe um mapa literal #{} e tenta construir uma instância validada. O retorno é sempre um Result<Schema, str>: Result::Ok com a instância em caso de sucesso, ou Result::Err com uma mensagem descritiva quando algum campo está ausente ou com tipo incorreto. Consuma o resultado com match, unwrap, unwrap_or, is_ok ou is_err.

Point.parse com mapa completo retorna Ok; mapa incompleto retorna Err.

03-parse-validation.zolo
Playground
// 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

O caminho inverso é instancia.to_map(), que serializa todos os campos de volta para um mapa — pronto para enviar pela rede, gravar em arquivo ou codificar como JSON. Junto com parse, ele forma o ciclo completo de validação e serialização:

Rect.to_map() acessa os campos pelo mapa; Point.to_map() + json.encode fecha o ciclo.

05-to-map.zolo
Playground
// 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)

Desafio

Crie um schema Email { address: str } e tente parsear um mapa vazio #{}. Imprima a mensagem de erro recebida. Em seguida, parse um mapa válido, converta com to_map() e verifique que m["address"] retorna o valor original.

Buscar no Zolo

9 resultados

enespt-br