Oneof, mappe e tipi well-known
Modelli dati flessibili ed evolutivi con i campi oneof di protobuf, le mappe e i tipi standard well-known come Timestamp, Duration e Any.
Oneof, mappe e tipi well-known è una lezione gRPC & High Performance APIs gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento gRPC & High Performance APIs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso gRPC & High Performance APIs include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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
Domande Frequenti
La lezione «Oneof, mappe e tipi well-known» è gratuita?
Sì — il testo completo di «Oneof, mappe e tipi well-known» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso gRPC & High Performance APIs, passa a CoddyKit PRO. Il corso gRPC & High Performance APIs include 4 lezioni in totale.
Cosa imparerò in «Oneof, mappe e tipi well-known»?
Modelli dati flessibili ed evolutivi con i campi oneof di protobuf, le mappe e i tipi standard well-known come Timestamp, Duration e Any. Eserciti gRPC & High Performance APIs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare gRPC & High Performance APIs?
Non è richiesta alcuna esperienza precedente. gRPC & High Performance APIs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Oneof, mappe e tipi well-known»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione gRPC & High Performance APIs?
Sì. Ogni lezione gRPC & High Performance APIs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Procedure consigliate per Protobuf
- Strategie per l'evoluzione degli schemi
- Opzioni Protobuf personalizzate
- Oneof, mappe e tipi well-known