Working with Scalar Data Types

1. Using Integer Types

TypeRangeWireBest For
int32−2³¹ … 2³¹−1varintPositive small ints
int64−2⁶³ … 2⁶³−1varintIDs, timestamps
uint32 / uint640 … 2³² / 2⁶⁴varintCounters, sizes
Warning: int32/int64 encode negative numbers as 10 bytes. Use sint32/sint64 for negatives.

2. Using Fixed-Size Integers

TypeSizeBest For
fixed32Always 4 bytesValues frequently > 2²⁸
fixed64Always 8 bytesHashes, large IDs
sfixed32/644 / 8 bytes signedPredictable size for negatives

3. Using Signed Integers

TypeEncodingUse When
sint32ZigZag → varintLikely negative 32-bit
sint64ZigZag → varintLikely negative 64-bit

Example: Signed delta

message TempReading {
  sint32 delta_celsius = 1;   // often negative
}

4. Using Floating Point Types

TypePrecisionSize
float~7 digits4 bytes
double~15 digits8 bytes
Warning: Never use floats for currency. Use int64 minor units (cents) or a Money message.

5. Using Boolean Type

PropertyValue
Wire size1 byte (varint)
Defaultfalse (not sent on wire)
NamingPositive predicate: is_active, has_email

6. Using String Type

PropertyDetail
EncodingUTF-8, length-delimited
MaxPractically limited by message-size cap (default 4 MB client recv)
Invalid UTF-8Decoders reject

7. Using Bytes Type

UseWhy
Binary blobsNo UTF-8 validation overhead
Pre-encoded dataImages, signatures, encrypted payloads
Cryptographic keysAvoid base64 round-trip

8. Understanding Type Encoding

Wire TypeValueTypes
VARINT0int*, uint*, sint*, bool, enum
I641fixed64, sfixed64, double
LEN2string, bytes, message, packed repeated
I325fixed32, sfixed32, float

9. Choosing Appropriate Types

NeedType
DB primary keystring (UUID) or int64
Moneyint64 minor units + currency code
Timestampgoogle.protobuf.Timestamp
Durationgoogle.protobuf.Duration
Enumsenum with UNSPECIFIED = 0
Binarybytes

10. Understanding Default Values

BehaviorDetail
Singular scalar at defaultOmitted from wire
Field number conflict on defaultReceiver sees default — looks the same
WorkaroundUse optional or a wrapper type (e.g. google.protobuf.Int32Value)