Oneof, mapas y tipos conocidos
Modele datos flexibles y evolutivos con campos oneof, mapas y tipos conocidos estándar de protobuf, como Timestamp, Duration y Any.
Oneof, mapas y tipos conocidos es una lección gratuita de gRPC & High Performance APIs en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de gRPC & High Performance APIs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de gRPC & High Performance APIs incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Beyond Plain Scalar Fields
Real schemas need more than strings and ints: mutually exclusive choices, key/value collections, and standard date/time types. Protobuf provides oneof, maps, and well-known types.
The oneof Construct
A oneof groups fields where at most one can be set at a time. Setting one clears the others, and only the active field is sent on the wire.
message Contact {
oneof method {
string email = 1;
string phone = 2;
}
}Reading a oneof
Generated code gives a way to check which case is set, usually a case enum or accessor, so you branch on the active field.
switch c.Method.(type) {
case *Contact_Email: useEmail(c.GetEmail())
case *Contact_Phone: usePhone(c.GetPhone())
}Map Fields
A map stores key/value pairs. Keys must be scalar (string/int); values can be any type except another map.
message Config {
map<string, string> settings = 1;
}How Maps Work on the Wire
Maps are sugar over a repeated message of key/value entries. Order is not guaranteed, and duplicate keys keep the last value — important when evolving schemas.
Well-Known Types
Protobuf ships standard types in google/protobuf/:
Timestamp— a point in timeDuration— a length of timeAny— a packed arbitrary messageStruct— dynamic JSON-like data
Timestamp and Duration
Prefer these over raw int seconds for clarity and tooling support. They map to native time types in most languages.
import 'google/protobuf/timestamp.proto';
message Event {
google.protobuf.Timestamp created_at = 1;
}Using Any
Any wraps any message plus a type URL, letting you carry heterogeneous payloads. The rich error model and reflection both use it.
import 'google/protobuf/any.proto';
message Envelope {
google.protobuf.Any payload = 1;
}FieldMask for Partial Updates
FieldMask lists which fields a request touches, enabling partial updates (PATCH-style) without ambiguity over unset vs default values.
// paths: ['name', 'email']Wrappers for Nullability
Proto3 scalars cannot distinguish unset from zero. Wrapper types like Int32Value and StringValue add explicit nullability when you need it.
Evolution Tips
When evolving these constructs:
- Add new fields to a
oneofsafely; do not reuse tag numbers - Maps: avoid changing value type
- Well-known types are stable; prefer them over hand-rolled equivalents
Quick Check
Test your advanced protobuf knowledge.
Recap
You learned advanced protobuf constructs:
oneofmodels mutually exclusive fieldsmapstores key/value pairs (sugar over repeated entries)- Well-known types:
Timestamp,Duration,Any,Struct FieldMaskenables partial updates; wrappers add nullability- Evolve carefully without reusing tag numbers
Preguntas frecuentes
¿La lección «Oneof, mapas y tipos conocidos» es gratis?
Sí — el texto completo de «Oneof, mapas y tipos conocidos» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de gRPC & High Performance APIs, actualiza a CoddyKit PRO. El curso de gRPC & High Performance APIs incluye 4 lecciones en total.
¿Qué aprenderé en «Oneof, mapas y tipos conocidos»?
Modele datos flexibles y evolutivos con campos oneof, mapas y tipos conocidos estándar de protobuf, como Timestamp, Duration y Any. Practicas gRPC & High Performance APIs con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar gRPC & High Performance APIs?
No se requiere experiencia previa. gRPC & High Performance APIs en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Oneof, mapas y tipos conocidos»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de gRPC & High Performance APIs?
Sí. Cada lección de gRPC & High Performance APIs incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Prácticas recomendadas para Protobuf
- Estrategias de evolución de esquemas
- Opciones personalizadas de Protobuf
- Oneof, mapas y tipos conocidos