Structs: Derive y Validación
En esta página
@derive genera implementaciones estándar de traits para un struct sin código
manual. Los traits disponibles son Eq (comparación con ==), Clone
(método .clone()) y Debug (impresión estructurada mediante print). Varios
traits pueden combinarse en una sola línea:
Eq en Color, Clone en Config, y los tres traits juntos en Vec3.
// Feature: `@derive(Trait, ...)` — generates common implementations
// Syntax: `@derive(Eq)`, `@derive(Clone)`, `@derive(Debug)`, or multiple.
// When to use: structs where you want to compare (`==`), copy (`.clone()`),
// or print (`tostring`) without writing boilerplate.
@derive(Eq)
struct Color {
r: int,
g: int,
b: int,
}
let red = Color { r: 255, g: 0, b: 0 }
let also_red = Color { r: 255, g: 0, b: 0 }
let blue = Color { r: 0, g: 0, b: 255 }
print("red == also_red? {red == also_red}")
// expected: red == also_red? true
print("red == blue? {red == blue}")
// expected: red == blue? false
@derive(Clone)
struct Config {
host: str,
port: int,
}
let cfg = Config { host: "localhost", port: 8080 }
let backup = cfg.clone()
print("backup = {backup.host}:{backup.port}")
// expected: backup = localhost:8080
// Multi-derive — several capabilities in a single line.
@derive(Debug, Clone, Eq)
struct Vec3 {
x: float,
y: float,
z: float,
}
let v = Vec3 { x: 1.0, y: 2.0, z: 3.0 }
let w = v.clone()
print(v)
// expected: Vec3 { x: 1.0, y: 2.0, z: 3.0 }
print("v == w? {v == w}")
// expected: v == w? true
@validate genera el método .validate() en el struct. Recorre todos los
campos y devuelve true si ninguno es nil — suficiente para validar payloads
de formularios y cuerpos de solicitudes de API antes de procesarlos:
Validación simple de struct y composición con @serialize.
// Feature: `@validate` — generates `.validate()` that checks for non-nil fields
// Syntax: `@validate` on a struct. The method returns `true` if all
// fields are non-nil.
// When to use: simple payload validation (form, API body) before
// processing.
@validate
struct Registration {
username: str,
email: str,
age: int,
}
let valid = Registration { username: "alice", email: "[email protected]", age: 25 }
print("valid? {valid.validate()}")
// expected: valid? true
// `@validate` also pairs well with @serialize/@deserialize.
@validate
@serialize
struct LoginRequest {
user: str,
password: str,
}
let req = LoginRequest { user: "bob", password: "secret" }
print("login valid? {req.validate()}")
// expected: login valid? true
print("login json = {req.to_json()}")
// expected: login json = {"user":"bob","password":"secret"}
Desafío
Crea un struct Address con los campos street, city y zip, anótalo con
@derive(Debug, Eq) y @validate. Instancia dos objetos iguales y confirma
que == devuelve true y .validate() devuelve true.
Consulta también