0Pricing
gRPC & High Performance APIs · Aula

Oneof, mapas e tipos conhecidos

Modele dados flexíveis e evolutivos com campos oneof do protobuf, mapas e tipos conhecidos padrão, como MarcaTemporal, Duração e Qualquer.

Oneof, mapas e tipos conhecidos é uma aula grátis de gRPC & High Performance APIs no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de gRPC & High Performance APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de gRPC & High Performance APIs inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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 time
  • Duration — a length of time
  • Any — a packed arbitrary message
  • Struct — 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 oneof safely; 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:

  • oneof models mutually exclusive fields
  • map stores key/value pairs (sugar over repeated entries)
  • Well-known types: Timestamp, Duration, Any, Struct
  • FieldMask enables partial updates; wrappers add nullability
  • Evolve carefully without reusing tag numbers

Perguntas Frequentes

A aula “Oneof, mapas e tipos conhecidos” é grátis?

Sim — o texto completo de “Oneof, mapas e tipos conhecidos” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de gRPC & High Performance APIs, atualize para CoddyKit PRO. O curso de gRPC & High Performance APIs inclui 4 aulas no total.

O que vou aprender em “Oneof, mapas e tipos conhecidos”?

Modele dados flexíveis e evolutivos com campos oneof do protobuf, mapas e tipos conhecidos padrão, como MarcaTemporal, Duração e Qualquer. Você pratica gRPC & High Performance APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar gRPC & High Performance APIs?

Nenhuma experiência prévia é necessária. gRPC & High Performance APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Oneof, mapas e tipos conhecidos”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de gRPC & High Performance APIs?

Sim. Cada aula de gRPC & High Performance APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Melhores práticas de Protobuf
  2. Estratégias de evolução de esquemas
  3. Opções personalizadas do Protobuf
  4. Oneof, mapas e tipos conhecidos
← Voltar para gRPC & High Performance APIs