Oneof, карты и общеизвестные типы
Моделируйте гибкие, развивающиеся данные с помощью полей protobuf oneof, карт и стандартных общеизвестных типов, таких как Timestamp, Duration и Any.
«Oneof, карты и общеизвестные типы» — бесплатный урок gRPC & High Performance APIs на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения gRPC & High Performance APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс gRPC & High Performance APIs содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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
Часто задаваемые вопросы
Урок «Oneof, карты и общеизвестные типы» бесплатный?
Да — полный текст урока «Oneof, карты и общеизвестные типы» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс gRPC & High Performance APIs, подпишись на CoddyKit PRO. Курс gRPC & High Performance APIs содержит 4 уроков всего.
Чему я научусь в уроке «Oneof, карты и общеизвестные типы»?
Моделируйте гибкие, развивающиеся данные с помощью полей protobuf oneof, карт и стандартных общеизвестных типов, таких как Timestamp, Duration и Any. Ты практикуешь gRPC & High Performance APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать gRPC & High Performance APIs?
Предыдущий опыт не требуется. gRPC & High Performance APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Oneof, карты и общеизвестные типы»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке gRPC & High Performance APIs?
Да. Каждый урок gRPC & High Performance APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Лучшие практики Protobuf
- Стратегии развития схем
- Пользовательские параметры Protobuf
- Oneof, карты и общеизвестные типы