# C++ Generated Code Guide

Describes exactly what C++ code the protocol buffer compiler generates for any given protocol definition.

Any differences between proto2, proto3, and editions generated code are highlighted. Note that these differences are in the generated code as described in this document, not the base message classes/interfaces, which are the same in all versions. You should read the [proto2 language guide](https://protobuf.dev/programming-guides/proto2), [proto3 language guide](https://protobuf.dev/programming-guides/proto3), or [edition 2023 language guide](https://protobuf.dev/programming-guides/editions) before reading this document.

## Compiler Invocation

The protocol buffer compiler produces C++ output when invoked with the `--cpp_out=` command-line flag. The parameter to the `--cpp_out=` option is the directory where you want the compiler to write your C++ output. The compiler creates a header file and an implementation file for each `.proto` file input. The names of the output files are computed by taking the name of the `.proto` file and making two changes:

  * The extension (`.proto`) is replaced with either `.pb.h` or `.pb.cc` for the header or implementation file, respectively.
  * The proto path (specified with the `--proto_path=` or `-I` command-line flag) is replaced with the output path (specified with the `--cpp_out=` flag).

So, for example, let’s say you invoke the compiler as follows:

    protoc --proto_path=src --cpp_out=build/gen src/foo.proto src/bar/baz.proto

The compiler will read the files `src/foo.proto` and `src/bar/baz.proto` and produce four output files: `build/gen/foo.pb.h`, `build/gen/foo.pb.cc`, `build/gen/bar/baz.pb.h`, `build/gen/bar/baz.pb.cc`. The compiler will automatically create the directory `build/gen/bar` if necessary, but it will _not_ create `build` or `build/gen`; they must already exist.

## Packages

If a `.proto` file contains a `package` declaration, the entire contents of the file will be placed in a corresponding C++ namespace. For example, given the `package` declaration:

    package foo.bar;

All declarations in the file will reside in the `foo::bar` namespace.

## Messages

Given a simple message declaration:

    message Foo {}

The protocol buffer compiler generates a class called `Foo`, which publicly derives from [`google::protobuf::Message`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.message). The class is a concrete class; no pure-virtual methods are left unimplemented. Methods that are virtual in `Message` but not pure-virtual may or may not be overridden by `Foo`, depending on the optimization mode. By default, `Foo` implements specialized versions of all methods for maximum speed. However, if the `.proto` file contains the line:

    option optimize_for = CODE_SIZE;

then `Foo` will override only the minimum set of methods necessary to function and rely on reflection-based implementations of the rest. This significantly reduces the size of the generated code, but also reduces performance. Alternatively, if the `.proto` file contains:

    option optimize_for = LITE_RUNTIME;

then `Foo` will include fast implementations of all methods, but will implement the [`google::protobuf::MessageLite`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.message_lite) interface, which only contains a subset of the methods of `Message`. In particular, it does not support descriptors or reflection. However, in this mode, the generated code only needs to link against `libprotobuf-lite.so` (`libprotobuf-lite.lib` on Windows) instead of `libprotobuf.so` (`libprotobuf.lib`). The “lite” library is much smaller than the full library, and is more appropriate for resource-constrained systems such as mobile phones.

You should _not_ create your own `Foo` subclasses. If you subclass this class and override a virtual method, the override may be ignored, as many generated method calls are de-virtualized to improve performance.

The `Message` interface defines methods that let you check, manipulate, read, or write the entire message, including parsing from and serializing to binary strings.

  * `bool ParseFromString(::absl::string_view data)`: Parse the message from the given serialized binary string (also known as wire format).
  * `bool SerializeToString(string* output) const`: Serialize the given message to a binary string.
  * `string DebugString()`: Return a string giving the `text_format` representation of the proto (should only be used for debugging).

In addition to these methods, the `Foo` class defines the following methods:

  * `Foo()`: Default constructor.
  * `~Foo()`: Default destructor.
  * `Foo(const Foo& other)`: Copy constructor.
  * `Foo(Foo&& other)`: Move constructor.
  * `Foo& operator=(const Foo& other)`: Assignment operator.
  * `Foo& operator=(Foo&& other)`: Move-assignment operator.
  * `void Swap(Foo* other)`: Swap content with another message.
  * `const UnknownFieldSet& unknown_fields() const`: Returns the set of unknown fields encountered while parsing this message. If `option optimize_for = LITE_RUNTIME` is specified in the `.proto` file, then the return type changes to `std::string&`.
  * `UnknownFieldSet* mutable_unknown_fields()`: Returns a pointer to the mutable set of unknown fields encountered while parsing this message. If `option optimize_for = LITE_RUNTIME` is specified in the `.proto` file, then the return type changes to `std::string*`.

**Note:** The copy constructor and assignment operator perform a deep copy of the message data. This ensures that each message object owns and manages its own copy of the data, preventing issues like double frees or use-after-free errors. This behavior is consistent with standard C++ practice for objects that own their data, such as `std::vector`. For developers coming from languages with different copy semantics (such as JavaScript or TypeScript, where shallow copies might be more common), it is important to note that modifications to a copied message will not affect the original message, and vice-versa.

The class also defines the following static methods:

  * `static const Descriptor* descriptor()`: Returns the type’s descriptor. This contains information about the type, including what fields it has and what their types are. This can be used with [reflection](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.message#Reflection) to inspect fields programmatically.
  * `static const Foo& default_instance()`: Returns a const singleton instance of `Foo` which is identical to a newly-constructed instance of `Foo` (so all singular fields are unset and all repeated fields are empty). Note that the default instance of a message can be used as a factory by calling its `New()` method.

### Abseil flag support

`Message` objects have native support for Abseil’s flag parse/unparse logic. They can be used as the type for `ABSL_FLAG` declarations. The flag syntax is `:format,options...:value` where:

  * `format` is one of `text`, `serialized`.
  * `options` is a possibly-empty list of options. Each format has its supported options.
  * `value` is the payload in the specified format.

The valid options are:

  * For `text`:
    * `base64`: indicates that `value` is encoded as base64.
    * `ignore_unknown`: when specified, unknown field/extensions are dropped. Otherwise, they cause a parse failure.
  * For `serialized`:
    * `base64`: indicates that `value` is encoded as base64. It is recommended to use `serialized` with `base64` given that passing binary data in shells is difficult and error prone.

Note that flag support for message types is not provided for `LITE_RUNTIME` configurations.

Example:

    ABSL_FLAG(MyProtoType, my_proto_config, {},
              "This is a proto config description.");

### Nested Types

A message can be declared inside another message. For example:

    message Foo {
      message Bar {}

In this case, the compiler generates two classes: `Foo` and `Foo_Bar`. In addition, the compiler generates a typedef inside `Foo` as follows:

    typedef Foo_Bar Bar;

This means that you can use the nested type’s class as if it was the nested class `Foo::Bar`. However, note that C++ does not allow nested types to be forward-declared. If you want to forward-declare `Bar` in another file and use that declaration, you must identify it as `Foo_Bar`.

## Fields

In addition to the methods described in the previous section, the protocol buffer compiler generates a set of accessor methods for each field defined within the message in the `.proto` file. These methods are in lower-case/snake-case, such as `has_foo()` and `clear_foo()`.

As well as accessor methods, the compiler generates an integer constant for each field containing its field number. The constant name is the letter `k`, followed by the field name converted to camel-case, followed by `FieldNumber`. For example, given the field `optional int32 foo_bar = 5;`, the compiler will generate the constant `static const int kFooBarFieldNumber = 5;`.

For field accessors returning a `const` reference, that reference may be invalidated when the next modifying access is made to the message. This includes calling any non-`const` accessor of any field, calling any non-`const` method inherited from `Message` or modifying the message through other ways (for example, by using the message as the argument of `Swap()`). Correspondingly, the address of the returned reference is only guaranteed to be the same across different invocations of the accessor if no modifying access was made to the message in the meantime.

For field accessors returning a pointer, that pointer may be invalidated when the next modifying or non-modifying access is made to the message. This includes, regardless of constness, calling any accessor of any field, calling any method inherited from `Message` or accessing the message through other ways (for example, by copying the message using the copy constructor). Correspondingly, the value of the returned pointer is never guaranteed to be the same across two different invocations of the accessor.

### Generated Fieldnames

[Reserved keywords](https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/compiler/cpp/helpers.cc#L4) are appended with an underscore in the generated output.

For example, the following proto3 definition syntax:

    message MyMessage {
      string false = 1;
      string myFalse = 2;

generates the following partial output:

      void clear_false_() ;
      const std::string& false_() const;
      void set_false_(Arg_&& arg, Args_... args);
      std::string* mutable_false_();
      PROTOBUF_NODISCARD std::string* release_false_();
      void set_allocated_false_(std::string* ptr);

      void clear_myfalse() ;
      const std::string& myfalse() const;
      void set_myfalse(Arg_&& arg, Args_... args);
      std::string* mutable_myfalse();
      PROTOBUF_NODISCARD std::string* release_myfalse();
      void set_allocated_myfalse(std::string* ptr);

### Explicit Presence Numeric Fields

For field definitions for numeric fields with [explicit presence](https://protobuf.dev/programming-guides/field_presence#presence-in-proto2-apis):

    int32 foo = 1;

The compiler will generate the following accessor methods:

  * `bool has_foo() const`: Returns `true` if the field is set.
  * `int32_t foo() const`: Returns the current value of the field. If the field is not set, returns the default value.
  * `void set_foo(::int32_t value)`: Sets the value of the field. After calling this, `has_foo()` will return `true` and `foo()` will return `value`.
  * `void clear_foo()`: Clears the value of the field. After calling this, `has_foo()` will return `false` and `foo()` will return the default value.

For other numeric field types (including `bool`), `int32_t` is replaced with the corresponding C++ type according to the [scalar value types table](https://protobuf.dev/programming-guides/editions#scalar).

### Implicit Presence Numeric Fields

For field definitions for numeric fields with [implicit presence](https://protobuf.dev/programming-guides/field_presence#presence-in-proto2-apis):

    int32 foo = 1;

The compiler will generate the following accessor methods:

  * `::int32_t foo() const`: Returns the current value of the field. If the field is not set, returns 0.
  * `void set_foo(::int32_t value)`: Sets the value of the field. After calling this, `foo()` will return `value`.
  * `void clear_foo()`: Clears the value of the field. After calling this, `foo()` will return 0.

For other numeric field types (including `bool`), `int32_t` is replaced with the corresponding C++ type according to the [scalar value types table](https://protobuf.dev/programming-guides/editions#scalar).

### Explicit Presence String/Bytes Fields

**Note:** As of edition 2023, if [`features.(pb.cpp).string_type`](https://protobuf.dev/editions/features#string_type) is set to `VIEW`, [string_view](https://protobuf.dev/reference/cpp/string-view#singular-view) APIs will be generated instead.

For these field definitions with [explicit presence](https://protobuf.dev/programming-guides/field_presence#presence-in-proto2-apis):

    string foo = 1;
    bytes foo = 2;

The compiler will generate the following accessor methods:

  * `bool has_foo() const`: Returns `true` if the field is set.

  * `const string& foo() const`: Returns the current value of the field. If the field is not set, returns the default value.

  * `void set_foo(...)`: Sets the value of the field. After calling this, `has_foo()` will return `true` and `foo()` will return a copy of `value`.

  * `string* mutable_foo()`: Returns a pointer to the mutable `string` object that stores the field’s value. If the field was not set prior to the call, then the returned string will be empty (_not_ the default value). After calling this, `has_foo()` will return `true` and `foo()` will return whatever value is written into the given string.

**Note:** This method will be removed in the new `string_view` APIs.

  * `void clear_foo()`: Clears the value of the field. After calling this, `has_foo()` will return `false` and `foo()` will return the default value.

  * `void set_allocated_foo(string* value)`: Sets the `string` object to the field and frees the previous field value if it exists. If the `string` pointer is not `NULL`, the message takes ownership of the allocated `string` object and `has_foo()` will return `true`. The message is free to delete the allocated `string` object at any time, so references to the object may be invalidated. Otherwise, if the `value` is `NULL`, the behavior is the same as calling `clear_foo()`.

  * `string* release_foo()`: Releases the ownership of the field and returns the pointer of the `string` object. After calling this, caller takes the ownership of the allocated `string` object, `has_foo()` will return `false`, and `foo()` will return the default value.

### Implicit Presence String/Bytes Fields

**Note:** As of edition 2023, if [`features.(pb.cpp).string_type`](https://protobuf.dev/editions/features#string_type) is set to `VIEW`, [string_view](https://protobuf.dev/reference/cpp/string-view#singular-view) APIs will be generated instead.

For these field definitions with [implicit presence](https://protobuf.dev/programming-guides/field_presence#presence-in-proto2-apis):

    string foo = 1 [features.field_presence = IMPLICIT];
    bytes foo = 1 [features.field_presence = IMPLICIT];

The compiler will generate the following accessor methods:

  * `const string& foo() const`: Returns the current value of the field. If the field is not set, returns the empty string/empty bytes.
  * `void set_foo(Arg_&& arg, Args_... args)`: Sets the value of the field. After calling this, `foo()` will return a copy of `value`.
  * `string* mutable_foo()`: Returns a pointer to the mutable `string` object that stores the field’s value. If the field was not set prior to the call, then the returned string will be empty. After calling this, `foo()` will return whatever value is written into the given string.
  * `void clear_foo()`: Clears the value of the field. After calling this, `foo()` will return the empty string/empty bytes.
  * `void set_allocated_foo(string* value)`: Sets the `string` object to the field and frees the previous field value if it exists. If the `string` pointer is not `NULL`, the message takes ownership of the allocated `string` object. The message is free to delete the allocated `string` object at any time, so references to the object may be invalidated. Otherwise, if the `value` is `NULL`, the behavior is the same as calling `clear_foo()`.
  * `string* release_foo()`: Releases the ownership of the field and returns the pointer of the `string` object. After calling this, caller takes the ownership of the allocated `string` object and `foo()` will return the empty string/empty bytes.

### Singular Bytes Fields with Cord Support

v23.0 added support for [`absl::Cord`](https://github.com/abseil/abseil-cpp/blob/master/absl/strings/cord.h) for singular `bytes` fields (including `oneof` fields). Singular `string`, `repeated string`, and `repeated bytes` fields do not support using `Cord`s.

To set a singular `bytes` field to store data using `absl::Cord`, use the following syntax:

    // edition (default settings)
    bytes foo = 25 [ctype=CORD];
    bytes foo = 26 [ctype=CORD, features.field_presence = IMPLICIT];

Using `cord` is not available for `repeated bytes` fields. Protoc ignores `[ctype=CORD]` settings on those fields.

The compiler will generate the following accessor methods:

  * `const ::absl::Cord& foo() const`: Returns the current value of the field. If the field is not set, returns an empty `Cord` (proto3) or the default value (proto2 and editions).
  * `void set_foo(const ::absl::Cord& value)`: Sets the value of the field. After calling this, `foo()` will return `value`.
  * `void set_foo(::absl::string_view value)`: Sets the value of the field. After calling this, `foo()` will return `value` as an `absl::Cord`.
  * `void clear_foo()`: Clears the value of the field. After calling this, `foo()` will return an empty `Cord` (proto3) or the default value (proto2 and editions).
  * `bool has_foo()`: Returns `true` if the field is set. Only applies for the `optional` field in proto3 and the explicit presence field in editions.

### Explicit Presence Enum Fields

Given the enum type:

    enum Bar {
      BAR_UNSPECIFIED = 0;
      BAR_VALUE = 1;
      BAR_OTHER_VALUE = 2;

For this field definition with [explicit presence](https://protobuf.dev/programming-guides/field_presence#presence-in-proto2-apis):

    Bar bar = 1;

The compiler will generate the following accessor methods:

  * `bool has_bar() const`: Returns `true` if the field is set.
  * `Bar bar() const`: Returns the current value of the field. If the field is not set, returns the default value.
  * `void set_bar(Bar value)`: Sets the value of the field. After calling this, `has_bar()` will return `true` and `bar()` will return `value`. In debug mode (i.e. NDEBUG is not defined), if `value` does not match any of the values defined for `Bar`, this method will abort the process.
  * `void clear_bar()`: Clears the value of the field. After calling this, `has_bar()` will return `false` and `bar()` will return the default value.

### Implicit Presence Enum Fields

Given the enum type:

    enum Bar {
      BAR_UNSPECIFIED = 0;
      BAR_VALUE = 1;
      BAR_OTHER_VALUE = 2;

For this field definition with [implicit presence](https://protobuf.dev/programming-guides/field_presence#presence-in-proto2-apis):

    Bar bar = 1;

The compiler will generate the following accessor methods:

  * `Bar bar() const`: Returns the current value of the field. If the field is not set, returns the default value (0).
  * `void set_bar(Bar value)`: Sets the value of the field. After calling this, `bar()` will return `value`.
  * `void clear_bar()`: Clears the value of the field. After calling this, `bar()` will return the default value.

### Explicit Presence Embedded Message Fields

Given the message type:

    message Bar {}

For this field definition with [explicit presence](https://protobuf.dev/programming-guides/field_presence#presence-in-proto2-apis):

    Bar bar = 1;

The compiler will generate the following accessor methods:

  * `bool has_bar() const`: Returns `true` if the field is set.
  * `const Bar& bar() const`: Returns the current value of the field. If the field is not set, returns a `Bar` with none of its fields set (possibly `Bar::default_instance()`).
  * `Bar* mutable_bar()`: Returns a pointer to the mutable `Bar` object that stores the field’s value. If the field was not set prior to the call, then the returned `Bar` will have none of its fields set (i.e. it will be identical to a newly-allocated `Bar`). After calling this, `has_bar()` will return `true` and `bar()` will return a reference to the same instance of `Bar`.
  * `void clear_bar()`: Clears the value of the field. After calling this, `has_bar()` will return `false` and `bar()` will return the default value.
  * `void set_allocated_bar(Bar* value)`: Sets the `Bar` object to the field and frees the previous field value if it exists. If the `Bar` pointer is not `NULL`, the message takes ownership of the allocated `Bar` object and `has_bar()` will return `true`. Otherwise, if the `Bar` is `NULL`, the behavior is the same as calling `clear_bar()`.
  * `Bar* release_bar()`: Releases the ownership of the field and returns the pointer of the `Bar` object. After calling this, caller takes the ownership of the allocated `Bar` object, `has_bar()` will return `false`, and `bar()` will return the default value.

### Repeated Numeric Fields

For this field definition:

    repeated int32 foo = 1;

The compiler will generate the following accessor methods:

  * `int foo_size() const`: Returns the number of elements currently in the field. To check for an empty set, consider using the [`empty()`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.repeated_field#RepeatedPtrField) method in the underlying `RepeatedField` instead of this method.
  * `int32_t foo(int index) const`: Returns the element at the given zero-based index. Calling this method with index outside of [0, foo_size()) yields undefined behavior.
  * `void set_foo(int index, int32_t value)`: Sets the value of the element at the given zero-based index.
  * `void add_foo(int32_t value)`: Appends a new element to the end of the field with the given value.
  * `void clear_foo()`: Removes all elements from the field. After calling this, `foo_size()` will return zero.
  * `const RepeatedField<int32_t>& foo() const`: Returns the underlying [`RepeatedField`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.repeated_field#RepeatedField) that stores the field’s elements. This container class provides STL-like iterators and other methods.
  * `RepeatedField<int32_t>* mutable_foo()`: Returns a pointer to the underlying mutable `RepeatedField` that stores the field’s elements. This container class provides STL-like iterators and other methods.

For other numeric field types (including `bool`), `int32_t` is replaced with the corresponding C++ type according to the [scalar value types table](https://protobuf.dev/programming-guides/editions#scalar).

### Repeated String Fields

**Note:** As of edition 2023, if [`features.(pb.cpp).string_type`](https://protobuf.dev/editions/features#string_type) is set to `VIEW`, [string_view](https://protobuf.dev/reference/cpp/string-view#singular-view) APIs will be generated instead.

For either of these field definitions:

    repeated string foo = 1;
    repeated bytes foo = 1;

The compiler will generate the following accessor methods:

  * `int foo_size() const`: Returns the number of elements currently in the field. To check for an empty set, consider using the [`empty()`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.repeated_field#RepeatedPtrField) method in the underlying `RepeatedField` instead of this method.
  * `const string& foo(int index) const`: Returns the element at the given zero-based index. Calling this method with index outside of [0, foo_size()-1] yields undefined behavior.
  * `void set_foo(int index, ::absl::string_view value)`: Sets the value of the element at the given zero-based index.
  * `void set_foo(int index, const string& value)`: Sets the value of the element at the given zero-based index.
  * `void set_foo(int index, string&& value)`: Sets the value of the element at the given zero-based index, moving from the passed string.
  * `void set_foo(int index, const char* value)`: Sets the value of the element at the given zero-based index using a C-style null-terminated string.
  * `void set_foo(int index, const char* value, int size)`: Sets the value of the element at the given zero-based index using a C-style string with an explicit size specified, rather than determined by looking for a null-terminator byte.
  * `string* mutable_foo(int index)`: Returns a pointer to the mutable `string` object that stores the value of the element at the given zero-based index. Calling this method with index outside of [0, foo_size()) yields undefined behavior.
  * `void add_foo(::absl::string_view value)`: Appends a new element to the end of the field with the given value.
  * `void add_foo(const string& value)`: Appends a new element to the end of the field with the given value.
  * `void add_foo(string&& value)`: Appends a new element to the end of the field, moving from the passed string.
  * `void add_foo(const char* value)`: Appends a new element to the end of the field using a C-style null-terminated string.
  * `void add_foo(const char* value, int size)`: Appends a new element to the end of the field using a string with an explicit size specified, rather than determined by looking for a null-terminator byte.
  * `string* add_foo()`: Adds a new empty string element to the end of the field and returns a pointer to it.
  * `void clear_foo()`: Removes all elements from the field. After calling this, `foo_size()` will return zero.
  * `const RepeatedPtrField<string>& foo() const`: Returns the underlying [`RepeatedPtrField`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.repeated_field#RepeatedPtrField) that stores the field’s elements. This container class provides STL-like iterators and other methods.
  * `RepeatedPtrField<string>* mutable_foo()`: Returns a pointer to the underlying mutable `RepeatedPtrField` that stores the field’s elements. This container class provides STL-like iterators and other methods.

### Repeated Enum Fields

Given the enum type:

    enum Bar {
      BAR_UNSPECIFIED = 0;
      BAR_VALUE = 1;
      BAR_OTHER_VALUE = 2;

For this field definition:

    repeated Bar bar = 1;

The compiler will generate the following accessor methods:

  * `int bar_size() const`: Returns the number of elements currently in the field. To check for an empty set, consider using the [`empty()`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.repeated_field#RepeatedPtrField) method in the underlying `RepeatedField` instead of this method.
  * `Bar bar(int index) const`: Returns the element at the given zero-based index. Calling this method with index outside of [0, bar_size()) yields undefined behavior.
  * `void set_bar(int index, Bar value)`: Sets the value of the element at the given zero-based index. In debug mode (i.e. NDEBUG is not defined), if `value` does not match any of the values defined for `Bar` and it is a closed enum, this method will abort the process.
  * `void add_bar(Bar value)`: Appends a new element to the end of the field with the given value. In debug mode (i.e. NDEBUG is not defined), if `value` does not match any of the values defined for `Bar`, this method will abort the process.
  * `void clear_bar()`: Removes all elements from the field. After calling this, `bar_size()` will return zero.
  * `const RepeatedField<int>& bar() const`: Returns the underlying [`RepeatedField`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.repeated_field#RepeatedField) that stores the field’s elements. This container class provides STL-like iterators and other methods.
  * `RepeatedField<int>* mutable_bar()`: Returns a pointer to the underlying mutable `RepeatedField` that stores the field’s elements. This container class provides STL-like iterators and other methods.

### Repeated Embedded Message Fields

Given the message type:

    message Bar {}

For this field definitions:

    repeated Bar bar = 1;

The compiler will generate the following accessor methods:

  * `int bar_size() const`: Returns the number of elements currently in the field. To check for an empty set, consider using the [`empty()`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.repeated_field#RepeatedPtrField) method in the underlying `RepeatedField` instead of this method.
  * `const Bar& bar(int index) const`: Returns the element at the given zero-based index. Calling this method with index outside of [0, bar_size()) yields undefined behavior.
  * `Bar* mutable_bar(int index)`: Returns a pointer to the mutable `Bar` object that stores the value of the element at the given zero-based index. Calling this method with index outside of [0, bar_size()) yields undefined behavior.
  * `Bar* add_bar()`: Adds a new element to the end of the field and returns a pointer to it. The returned `Bar` is mutable and will have none of its fields set (i.e. it will be identical to a newly-allocated `Bar`).
  * `void clear_bar()`: Removes all elements from the field. After calling this, `bar_size()` will return zero.
  * `const RepeatedPtrField<Bar>& bar() const`: Returns the underlying [`RepeatedPtrField`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.repeated_field#RepeatedPtrField) that stores the field’s elements. This container class provides STL-like iterators and other methods.
  * `RepeatedPtrField<Bar>* mutable_bar()`: Returns a pointer to the underlying mutable `RepeatedPtrField` that stores the field’s elements. This container class provides STL-like iterators and other methods.

### Oneof Numeric Fields

For this oneof field definition:

    oneof example_name {
        int32 foo = 1;
        ...

The compiler will generate the following accessor methods:

  * `bool has_foo() const`: Returns `true` if oneof case is `kFoo`.
  * `int32 foo() const`: Returns the current value of the field if oneof case is `kFoo`. Otherwise, returns the default value.
  * `void set_foo(int32 value)`:
    * If any other oneof field in the same oneof is set, calls `clear_example_name()`.
    * Sets the value of this field and sets the oneof case to `kFoo`.
    * `has_foo()` will return true, `foo()` will return `value`, and `example_name_case()` will return `kFoo`.
  * `void clear_foo()`:
    * Nothing will be changed if oneof case is not `kFoo`.
    * If oneof case is `kFoo`, clears the value of the field and oneof case. `has_foo()` will return `false`, `foo()` will return the default value and `example_name_case()` will return `EXAMPLE_NAME_NOT_SET`.

For other numeric field types (including `bool`),`int32_t` is replaced with the corresponding C++ type according to the [scalar value types table](https://protobuf.dev/programming-guides/editions#scalar).

### Oneof String Fields

**Note:** As of edition 2023, [string_view](https://protobuf.dev/reference/cpp/string-view#oneof-view) APIs may be generated instead.

For any of these oneof field definitions:

    oneof example_name {
        string foo = 1;
        ...
    oneof example_name {
        bytes foo = 1;
        ...

The compiler will generate the following accessor methods:

  * `bool has_foo() const`: Returns `true` if the oneof case is `kFoo`.
  * `const string& foo() const`: Returns the current value of the field if the oneof case is `kFoo`. Otherwise, returns the default value.
  * `void set_foo(::absl::string_view value)`:
    * If any other oneof field in the same oneof is set, calls `clear_example_name()`.
    * Sets the value of this field and sets the oneof case to `kFoo`.
    * `has_foo()` will return `true`, `foo()` will return a copy of `value` and `example_name_case()` will return `kFoo`.
  * `void set_foo(const string& value)`: Like the first `set_foo()`, but copies from a const string reference.
  * `void set_foo(string&& value)`: Like the first `set_foo()`, but moving from the passed string.
  * `void set_foo(const char* value)`: Like the first `set_foo()`, but copies from a C-style null-terminated string.
  * `void set_foo(const char* value, int size)`: Like the first `set_foo()`, but copies from a string with an explicit size specified, rather than determined by looking for a null-terminator byte.
  * `string* mutable_foo()`:
    * If any other oneof field in the same oneof is set, calls `clear_example_name()`.
    * Sets the oneof case to `kFoo` and returns a pointer to the mutable string object that stores the field’s value. If the oneof case was not `kFoo` prior to the call, then the returned string will be empty (not the default value).
    * `has_foo()` will return `true`, `foo()` will return whatever value is written into the given string and `example_name_case()` will return `kFoo`.
  * `void clear_foo()`:
    * If the oneof case is not `kFoo`, nothing will be changed.
    * If the oneof case is `kFoo`, frees the field and clears the oneof case. `has_foo()` will return `false`, `foo()` will return the default value, and `example_name_case()` will return `EXAMPLE_NAME_NOT_SET`.
  * `void set_allocated_foo(string* value)`:
    * Calls `clear_example_name()`.
    * If the string pointer is not `NULL`: Sets the string object to the field and sets the oneof case to `kFoo`. The message takes ownership of the allocated string object, `has_foo()` will return `true` and `example_name_case()` will return `kFoo`.
    * If the string pointer is `NULL`, `has_foo()` will return `false` and `example_name_case()` will return `EXAMPLE_NAME_NOT_SET`.
  * `string* release_foo()`:
    * Returns `NULL` if oneof case is not `kFoo`.
    * Clears the oneof case, releases the ownership of the field, and returns the pointer of the string object. After calling this, caller takes the ownership of the allocated string object, `has_foo()` will return false, `foo()` will return the default value, and `example_name_case()` will return `EXAMPLE_NAME_NOT_SET`.

### Oneof Enum Fields

Given the enum type:

    enum Bar {
      BAR_UNSPECIFIED = 0;
      BAR_VALUE = 1;
      BAR_OTHER_VALUE = 2;

For the oneof field definition:

    oneof example_name {
        Bar bar = 1;
        ...

The compiler will generate the following accessor methods:

  * `bool has_bar() const`: Returns `true` if oneof case is `kBar`.
  * `Bar bar() const`: Returns the current value of the field if oneof case is `kBar`. Otherwise, returns the default value.
  * `void set_bar(Bar value)`:
    * If any other oneof field in the same oneof is set, calls `clear_example_name()`.
    * Sets the value of this field and sets the oneof case to `kBar`.
    * `has_bar()` will return `true`, `bar()` will return `value` and `example_name_case()` will return `kBar`.
    * In debug mode (that is, NDEBUG is not defined), if `value` does not match any of the values defined for `Bar` and it is a closed enum, this method will abort the process.
  * `void clear_bar()`:
    * Nothing will be changed if the oneof case is not `kBar`.
    * If the oneof case is `kBar`, clears the value of the field and the oneof case. `has_bar()` will return `false`, `bar()` will return the default value and `example_name_case()` will return `EXAMPLE_NAME_NOT_SET`.

### Oneof Embedded Message Fields

Given the message type:

    message Bar {}

For the oneof field definition:

    oneof example_name {
        Bar bar = 1;
        ...

The compiler will generate the following accessor methods:

  * `bool has_bar() const`: Returns true if oneof case is `kBar`.
  * `const Bar& bar() const`: Returns the current value of the field if oneof case is `kBar`. Otherwise, returns a Bar with none of its fields set (possibly `Bar::default_instance()`).
  * `Bar* mutable_bar()`:
    * If any other oneof field in the same oneof is set, calls `clear_example_name()`.
    * Sets the oneof case to `kBar` and returns a pointer to the mutable Bar object that stores the field’s value. If the oneof case was not `kBar` prior to the call, then the returned Bar will have none of its fields set (that is, it will be identical to a newly-allocated Bar).
    * After calling this, `has_bar()` will return `true`, `bar()` will return a reference to the same instance of `Bar` and `example_name_case()` will return `kBar`.
  * `void clear_bar()`:
    * Nothing will be changed if the oneof case is not `kBar`.
    * If the oneof case equals `kBar`, frees the field and clears the oneof case. `has_bar()` will return `false`, `bar()` will return the default value and `example_name_case()` will return `EXAMPLE_NAME_NOT_SET`.
  * `void set_allocated_bar(Bar* bar)`:
    * Calls `clear_example_name()`.
    * If the `Bar` pointer is not `NULL`: Sets the `Bar` object to the field and sets the oneof case to `kBar`. The message takes ownership of the allocated `Bar` object, has_bar() will return true and `example_name_case()` will return `kBar`.
    * If the pointer is `NULL`, `has_bar()` will return `false` and `example_name_case()` will return `EXAMPLE_NAME_NOT_SET`. (The behavior is like calling `clear_example_name()`)
  * `Bar* release_bar()`:
    * Returns `NULL` if oneof case is not `kBar`.
    * If the oneof case is `kBar`, clears the oneof case, releases the ownership of the field and returns the pointer of the `Bar` object. After calling this, caller takes the ownership of the allocated `Bar` object, `has_bar()` will return `false`, `bar()` will return the default value, and `example_name_case()` will return `EXAMPLE_NAME_NOT_SET`.

### Map Fields

For this map field definition:

    map<int32, int32> weight = 1;

The compiler will generate the following accessor methods:

  * `const google::protobuf::Map<int32, int32>& weight();`: Returns an immutable `Map`.
  * `google::protobuf::Map<int32, int32>* mutable_weight();`: Returns a mutable `Map`.

A [`google::protobuf::Map`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.map) is a special container type used in protocol buffers to store map fields. As you can see from its interface below, it uses a commonly-used subset of `std::map` and `std::unordered_map` methods.

#### Note

These maps are unordered.

    template<typename Key, typename T> {
    class Map {
      // Member types
      typedef Key key_type;
      typedef T mapped_type;
      typedef MapPair< Key, T > value_type;

      // Iterators
      iterator begin();
      const_iterator begin() const;
      const_iterator cbegin() const;
      iterator end();
      const_iterator end() const;
      const_iterator cend() const;
      // Capacity
      int size() const;
      bool empty() const;

      // Element access
      T& operator[](const Key& key);
      const T& at(const Key& key) const;
      T& at(const Key& key);

      // Lookup
      bool contains(const Key& key) const;
      int count(const Key& key) const;
      const_iterator find(const Key& key) const;
      iterator find(const Key& key);

      // Modifiers
      pair<iterator, bool> insert(const value_type& value);
      template<class InputIt>
      void insert(InputIt first, InputIt last);
      size_type erase(const Key& Key);
      iterator erase(const_iterator pos);
      iterator erase(const_iterator first, const_iterator last);
      void clear();

      // Copy
      Map(const Map& other);
      Map& operator=(const Map& other);

The easiest way to add data is to use normal map syntax, for example:

    std::unique_ptr<ProtoName> my_enclosing_proto(new ProtoName);
    (*my_enclosing_proto->mutable_weight())[my_key] = my_value;

`pair<iterator, bool> insert(const value_type& value)` will implicitly cause a deep copy of the `value_type` instance. The most efficient way to insert a new value into a `google::protobuf::Map` is as follows:

    T& operator[](const Key& key): map[new_key] = new_mapped;

#### Using `google::protobuf::Map` with standard maps

`google::protobuf::Map` supports the same iterator API as `std::map` and `std::unordered_map`. If you don’t want to use `google::protobuf::Map` directly, you can convert a `google::protobuf::Map` to a standard map by doing the following:

    std::map<int32, int32> standard_map(message.weight().begin(),
                                        message.weight().end());

Note that this will make a deep copy of the entire map.

You can also construct a `google::protobuf::Map` from a standard map as follows:

    google::protobuf::Map<int32, int32> weight(standard_map.begin(), standard_map.end());

#### Parsing unknown values

On the wire, a .proto map is equivalent to a map entry message for each key/value pair, while the map itself is a repeated field of map entries. Like ordinary message types, it’s possible for a parsed map entry message to have unknown fields: for example a field of type `int64` in a map defined as `map<int32, string>`.

If there are unknown fields in the wire format of a map entry message, they will be discarded.

If there is an unknown enum value in the wire format of a map entry message, it’s handled differently in proto2, proto3, and editions. In proto2, the whole map entry message is put into the unknown field set of the containing message. In proto3, it is put into a map field as if it is a known enum value. With editions, by default it mirrors the proto3 behavior. If `features.enum_type` is set to `CLOSED`, then it mirrors the proto2 behavior.

## Any

Given an [`Any`](https://protobuf.dev/programming-guides/proto3#any) field like this:

    import "google/protobuf/any.proto";

    message ErrorStatus {
      string message = 1;
      google.protobuf.Any details = 2;

In our generated code, the getter for the `details` field returns an instance of `google::protobuf::Any`. This provides the following special methods to pack and unpack the `Any`’s values:

    class Any {
     public:
      // Packs the given message into this Any using the default type URL
      // prefix “type.googleapis.com”. Returns false if serializing the message failed.
      bool PackFrom(const google::protobuf::Message& message);

      // Packs the given message into this Any using the given type URL
      // prefix. Returns false if serializing the message failed.
      bool PackFrom(const google::protobuf::Message& message,
                    ::absl::string_view type_url_prefix);

      // Unpacks this Any to a Message. Returns false if this Any
      // represents a different protobuf type or parsing fails.
      bool UnpackTo(google::protobuf::Message* message) const;

      // Returns true if this Any represents the given protobuf type.
      template<typename T> bool Is() const;

## Oneof

Given a oneof definition like this:

    oneof example_name {
        int32 foo_int = 4;
        string foo_string = 9;
        ...

The compiler will generate the following C++ enum type:

    enum ExampleNameCase {
      kFooInt = 4,
      kFooString = 9,
      EXAMPLE_NAME_NOT_SET = 0

In addition, it will generate these methods:

  * `ExampleNameCase example_name_case() const`: Returns the enum indicating which field is set. Returns `EXAMPLE_NAME_NOT_SET` if none of them is set.
  * `void clear_example_name()`: Frees the object if the oneof field set uses a pointer (Message or String), and sets the oneof case to `EXAMPLE_NAME_NOT_SET`.

## Enumerations

**Note:** As of edition 2024, `string_view` APIs may be generated with certain feature settings. See [Enumeration Name Helper](https://protobuf.dev/reference/cpp/string-view#enum-name) for more on this topic.

Given an enum definition like:

    enum Foo {
      VALUE_A = 0;
      VALUE_B = 5;
      VALUE_C = 1234;

The protocol buffer compiler will generate a C++ enum type called `Foo` with the same set of values. In addition, the compiler will generate the following functions:

  * `const EnumDescriptor* Foo_descriptor()`: Returns the type’s descriptor, which contains information about what values this enum type defines.
  * `bool Foo_IsValid(int value)`: Returns `true` if the given numeric value matches one of `Foo`’s defined values. In the above example, it would return `true` if the input were 0, 5, or 1234.
  * `const string& Foo_Name(int value)`: Returns the name for given numeric value. Returns an empty string if no such value exists. If multiple values have this number, the first one defined is returned. In the above example, `Foo_Name(5)` would return `"VALUE_B"`.
  * `bool Foo_Parse(::absl::string_view name, Foo* value)`: If `name` is a valid value name for this enum, assigns that value into `value` and returns true. Otherwise returns false. In the above example, `Foo_Parse("VALUE_C", &some_foo)` would return true and set `some_foo` to 1234.
  * `const Foo Foo_MIN`: the smallest valid value of the enum (VALUE_A in the example).
  * `const Foo Foo_MAX`: the largest valid value of the enum (VALUE_C in the example).
  * `const int Foo_ARRAYSIZE`: always defined as `Foo_MAX + 1`.

**Be careful when casting integers to proto2 enums.** If an integer is cast to a proto2 enum value, the integer _must_ be one of the valid values for that enum, or the results may be undefined. If in doubt, use the generated `Foo_IsValid()` function to test if the cast is valid. Setting an enum-typed field of a proto2 message to an invalid value may cause an assertion failure. If an invalid enum value is read when parsing a proto2 message, it will be treated as an [unknown field](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.unknown_field_set). These semantics have been changed in proto3. It’s safe to cast any integer to a proto3 enum value as long as it fits into int32. Invalid enum values will also be kept when parsing a proto3 message and returned by enum field accessors.

**Be careful when using proto3 and editions enums in switch statements.** Proto3 and editions enums are open enum types with possible values outside the range of specified symbols. (Editions enums may be set to closed enums using the [`enum_type`](https://protobuf.dev/editions/features#enum_type) feature.) Unrecognized enum values for open enums types will be kept when parsing a message and returned by the enum field accessors. A switch statement on an open enum without a default case will not be able to catch all cases, even if all the known fields are listed. This could lead to unexpected behavior, including data corruption and runtime crashes. **Always add a default case or explicitly call `Foo_IsValid(int)` outside of the switch to handle unknown enum values.**

You can define an enum inside a message type. In this case, the protocol buffer compiler generates code that makes it appear that the enum type itself was declared nested inside the message’s class. The `Foo_descriptor()` and `Foo_IsValid()` functions are declared as static methods. In reality, the enum type itself and its values are declared at the global scope with mangled names, and are imported into the class’s scope with a `typedef` and a series of constant definitions. This is done only to get around problems with declaration ordering. Do not depend on the mangled top-level names; pretend the enum really is nested in the message class.

### Abseil flag support

Generated `enum` values have native support for Abseil’s flag parse/unparse logic. They can be used as the type for `ABSL_FLAG` declarations.

The flag parser supports both labels and numbers. Invalid labels/numbers will cause a parse failure.

## Extensions (proto2 and editions only)

Given a message with an extension range:

    message Foo {
      extensions 100 to 199;

The protocol buffer compiler will generate some additional methods for `Foo`: `HasExtension()`, `ExtensionSize()`, `ClearExtension()`, `GetExtension()`, `SetExtension()`, `MutableExtension()`, `AddExtension()`, `SetAllocatedExtension()` and `ReleaseExtension()`. Each of these methods takes, as its first parameter, an extension identifier (described later in this section), which identifies an extension field. The remaining parameters and the return value are exactly the same as those for the corresponding accessor methods that would be generated for a normal (non-extension) field of the same type as the extension identifier. (`GetExtension()` corresponds to the accessors with no special prefix.)

Given an extension definition:

    extend Foo {
      optional int32 bar = 123;
      repeated int32 repeated_bar = 124;
      optional Bar message_bar = 125;

For the singular extension field `bar`, the protocol buffer compiler generates an “extension identifier” called `bar`, which you can use with `Foo`’s extension accessors to access this extension, like so:

    Foo foo;
    assert(!foo.HasExtension(bar));
    foo.SetExtension(bar, 1);
    assert(foo.HasExtension(bar));
    assert(foo.GetExtension(bar) == 1);
    foo.ClearExtension(bar);
    assert(!foo.HasExtension(bar));

For the message extension field `message_bar`, if the field is not set `foo.GetExtension(message_bar)` returns a `Bar` with none of its fields set (possibly `Bar::default_instance()`).

Similarly, for the repeated extension field `repeated_bar`, the compiler generates an extension identifier called `repeated_bar`, which you can also use with `Foo`’s extension accessors:

    Foo foo;
    for (int i = 0; i < kSize; ++i) {
      foo.AddExtension(repeated_bar, i)
    assert(foo.ExtensionSize(repeated_bar) == kSize)
    for (int i = 0; i < kSize; ++i) {
      assert(foo.GetExtension(repeated_bar, i) == i)

(The exact implementation of extension identifiers is complicated and involves magical use of templates—however, you don’t need to worry about how extension identifiers work to use them.)

Extensions can be declared nested inside of another type. For example, a common pattern is to do something like this:

    message Baz {
      extend Foo {
        optional Baz foo_ext = 124;

In this case, the extension identifier `foo_ext` is declared nested inside `Baz`. It can be used as follows:

    Foo foo;
    Baz* baz = foo.MutableExtension(Baz::foo_ext);
    FillInMyBaz(baz);

## Arena Allocation

Arena allocation is a C++-only feature that helps you optimize your memory usage and improve performance when working with protocol buffers. Enabling arena allocation in your `.proto` adds additional code for working with arenas to your C++ generated code. You can find out more about the arena allocation API in the [Arena Allocation Guide](https://protobuf.dev/reference/cpp/arenas).

## Services

If the `.proto` file contains the following line:

    option cc_generic_services = true;

then the protocol buffer compiler will generate code based on the service definitions found in the file as described in this section. However, the generated code may be undesirable as it is not tied to any particular RPC system, and thus requires more levels of indirection than code tailored to one system. If you do NOT want this code to be generated, add this line to the file:

    option cc_generic_services = false;

If neither of the above lines are given, the option defaults to `false`, as generic services are deprecated. (Note that prior to 2.4.0, the option defaults to `true`)

RPC systems based on `.proto`-language service definitions should provide [plugins](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.compiler.plugin.pb) to generate code appropriate for the system. These plugins are likely to require that abstract services are disabled, so that they can generate their own classes of the same names.

The remainder of this section describes what the protocol buffer compiler generates when abstract services are enabled.

### Interface

Given a service definition:

    service Foo {
      rpc Bar(FooRequest) returns(FooResponse);

The protocol buffer compiler will generate a class `Foo` to represent this service. `Foo` will have a virtual method for each method defined in the service definition. In this case, the method `Bar` is defined as:

    virtual void Bar(RpcController* controller, const FooRequest* request,
                     FooResponse* response, Closure* done);

The parameters are equivalent to the parameters of `Service::CallMethod()`, except that the `method` argument is implied and `request` and `response` specify their exact type.

These generated methods are virtual, but not pure-virtual. The default implementations simply call `controller->SetFailed()` with an error message indicating that the method is unimplemented, then invoke the `done` callback. When implementing your own service, you must subclass this generated service and implement its methods as appropriate.

`Foo` subclasses the `Service` interface. The protocol buffer compiler automatically generates implementations of the methods of `Service` as follows:

  * `GetDescriptor`: Returns the service’s [`ServiceDescriptor`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.descriptor#ServiceDescriptor).
  * `CallMethod`: Determines which method is being called based on the provided method descriptor and calls it directly, down-casting the request and response messages objects to the correct types.
  * `GetRequestPrototype` and `GetResponsePrototype`: Returns the default instance of the request or response of the correct type for the given method.

The following static method is also generated:

  * `static ServiceDescriptor descriptor()`: Returns the type’s descriptor, which contains information about what methods this service has and what their input and output types are.

### Stub

The protocol buffer compiler also generates a “stub” implementation of every service interface, which is used by clients wishing to send requests to servers implementing the service. For the `Foo` service (described earlier), the stub implementation `Foo_Stub` will be defined. As with nested message types, a `typedef` is used so that `Foo_Stub` can also be referred to as `Foo::Stub`.

`Foo_Stub` is a subclass of `Foo` which also implements the following methods:

  * `Foo_Stub(RpcChannel* channel)`: Constructs a new stub which sends requests on the given channel.
  * `Foo_Stub(RpcChannel* channel, ChannelOwnership ownership)`: Constructs a new stub which sends requests on the given channel and possibly owns that channel. If `ownership` is `Service::STUB_OWNS_CHANNEL` then when the stub object is deleted it will delete the channel as well.
  * `RpcChannel* channel()`: Returns this stub’s channel, as passed to the constructor.

The stub additionally implements each of the service’s methods as a wrapper around the channel. Calling one of the methods simply calls `channel->CallMethod()`.

The Protocol Buffer library does not include an RPC implementation. However, it includes all of the tools you need to hook up a generated service class to any arbitrary RPC implementation of your choice. You need only provide implementations of [`RpcChannel`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.service#RpcChannel) and [`RpcController`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.service#RpcController). See the documentation for [`service.h`](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.service) for more information.

## Plugin Insertion Points

[Code generator plugins](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.compiler.plugin.pb) which want to extend the output of the C++ code generator may insert code of the following types using the given insertion point names. Each insertion point appears in both the `.pb.cc` file and the `.pb.h` file unless otherwise noted.

  * `includes`: Include directives.
  * `namespace_scope`: Declarations that belong in the file’s package/namespace, but not within any particular class. Appears after all other namespace-scope code.
  * `global_scope`: Declarations that belong at the top level, outside of the file’s namespace. Appears at the very end of the file.
  * `class_scope:TYPENAME`: Member declarations that belong in a message class. `TYPENAME` is the full proto name, such as `package.MessageType`. Appears after all other public declarations in the class. This insertion point appears only in the `.pb.h` file.

Do not generate code which relies on private class members declared by the standard code generator, as these implementation details may change in future versions of Protocol Buffers.


# Building Rust Protos

Describes how to build Rust protos using Cargo or Bazel.

## Cargo

See the [protobuf-example](https://docs.rs/crate/protobuf-example/latest/source/) crate for an example of how to set up your build.

## Bazel

The process of building a Rust library for a Protobuf definition is similar to other programming languages:

  1. Use the language-agnostic `proto_library` rule:

         proto_library(
             name = "person_proto",
             srcs = ["person.proto"],
         )

  2. Create a Rust library:

         load("//third_party/protobuf/rust:defs.bzl", "rust_proto_library")

         proto_library(
             name = "person_proto",
             srcs = ["person.proto"],
         )

         rust_proto_library(
             name = "person_rust_proto",
             deps = [":person_proto"],
         )

  3. Use the library by including it in a Rust binary:

         load("//devtools/rust/build_defs:rules.bzl", "rust_binary")
         load("//third_party/protobuf/rust:defs.bzl", "rust_proto_library")

         proto_library(
             name = "person_proto",
             srcs = ["person.proto"],
         )

         rust_proto_library(
             name = "person_rust_proto",
             deps = [":person_proto"],
         )

         rust_binary(
             name = "greet",
             srcs = ["greet.rs"],
             deps = [
                 ":person_rust_proto",
             ],
         )

#### Note

Don’t use `rust_upb_proto_library` or `rust_cc_proto_library` directly. `rust_proto_library` checks the global build flag to choose the appropriate backend for you.


# Python Generated Code Guide

Describes exactly what Python definitions the protocol buffer compiler generates for any given protocol definition.

Any differences between proto2, proto3, and Editions generated code are highlighted - note that these differences are in the generated code as described in this document, not the base message classes/interfaces, which are the same across all versions. You should read the [proto2 language guide](https://protobuf.dev/programming-guides/proto2), [proto3 language guide](https://protobuf.dev/programming-guides/proto3), and/or [Editions guide](https://protobuf.dev/programming-guides/editions) before reading this document.

The Python Protocol Buffers implementation is a little different from C++ and Java. In Python, the compiler only outputs code to build descriptors for the generated classes, and a [Python metaclass](https://docs.python.org/2.7/reference/datamodel#metaclasses) does the real work. This document describes what you get _after_ the metaclass has been applied.

## Compiler Invocation

The protocol buffer compiler produces Python output when invoked with the `--python_out=` command-line flag. The parameter to the `--python_out=` option is the directory where you want the compiler to write your Python output. The compiler creates a `.py` file for each `.proto` file input. The names of the output files are computed by taking the name of the `.proto` file and making two changes:

  * The extension (`.proto`) is replaced with `_pb2.py`.
  * The proto path (specified with the `--proto_path=` or `-I` command-line flag) is replaced with the output path (specified with the `--python_out=` flag).

So, for example, let’s say you invoke the compiler as follows:

    protoc --proto_path=src --python_out=build/gen src/foo.proto src/bar/baz.proto

The compiler will read the files `src/foo.proto` and `src/bar/baz.proto` and produce two output files: `build/gen/foo_pb2.py` and `build/gen/bar/baz_pb2.py`. The compiler will automatically create the directory `build/gen/bar` if necessary, but it will _not_ create `build` or `build/gen`; they must already exist.

Protoc can generate Python stubs (`.pyi`) using the `--pyi_out` parameter.

Note that if the `.proto` file or its path contains any characters which cannot be used in Python module names (for example, hyphens), they will be replaced with underscores. So, the file `foo-bar.proto` becomes the Python file `foo_bar_pb2.py`.

#### Tip

When outputting Python code, the protocol buffer compiler’s ability to output directly to ZIP archives is particularly convenient, as the Python interpreter is able to read directly from these archives if placed in the `PYTHONPATH`. To output to a ZIP file, simply provide an output location ending in `.zip`.

#### Note

The number 2 in the extension `_pb2.py` designates version 2 of Protocol Buffers. Version 1 was used primarily inside Google, though you might be able to find parts of it included in other Python code that was released before Protocol Buffers. Since version 2 of Python Protocol Buffers has a completely different interface, and since Python does not have compile-time type checking to catch mistakes, we chose to make the version number be a prominent part of generated Python file names. Currently proto2, proto3, and Editions all use `_pb2.py` for their generated files.

## Packages

The Python code generated by the protocol buffer compiler is completely unaffected by the package name defined in the `.proto` file. Instead, Python packages are identified by directory structure.

## Messages

Given a simple message declaration:

    message Foo {}

The protocol buffer compiler generates a class called `Foo`, which subclasses [`google.protobuf.Message`](https://googleapis.dev/python/protobuf/latest/google/protobuf/message.html#google.protobuf.message.Message). The class is a concrete class; no abstract methods are left unimplemented. Unlike C++ and Java, Python generated code is unaffected by the `optimize_for` option in the `.proto` file; in effect, all Python code is optimized for code size.

If the message’s name is a Python keyword, then its class will only be accessible via `getattr()`, as described in the Names that conflict with Python keywords section.

You should _not_ create your own `Foo` subclasses. Generated classes are not designed for subclassing and may lead to "fragile base class" problems. Besides, implementation inheritance is bad design.

Python message classes have no particular public members other than those defined by the `Message` interface and those generated for nested fields, messages, and enum types (described below). `Message` provides methods you can use to check, manipulate, read, or write the entire message, including parsing from and serializing to binary strings. In addition to these methods, the `Foo` class defines the following static methods:

  * `FromString(s)`: Returns a new message instance deserialized from the given string.

Note that you can also use the [`text_format`](https://googleapis.dev/python/protobuf/latest/google/protobuf/text_format.html) module to work with protocol messages in text format: for example, the `Merge()` method lets you merge an ASCII representation of a message into an existing message.

### Nested Types

A message can be declared inside another message. For example:

    message Foo {
      message Bar {}

In this case, the `Bar` class is declared as a static member of `Foo`, so you can refer to it as `Foo.Bar`.

## Well-known Types

Protocol buffers provides a number of [well-known types](https://protobuf.dev/reference/protobuf/google.protobuf) that you can use in your .proto files along with your own message types. Some WKT messages have special methods in addition to the usual protocol buffer message methods, as they subclass both [`google.protobuf.Message`](https://googleapis.dev/python/protobuf/latest/google/protobuf/message.html#google.protobuf.message.Message) and a WKT class.

### Any

For Any messages, you can call `Pack()` to pack a specified message into the current Any message, or `Unpack()` to unpack the current Any message into a specified message. For example:

    any_message.Pack(message)
    any_message.Unpack(message)

`Unpack()` also checks the descriptor of the passed-in message object against the stored one and returns `False` if they don’t match and does not attempt any unpacking; `True` otherwise.

You can also call the `Is()` method to check if the Any message represents the given protocol buffer type. For example:

    assert any_message.Is(message.DESCRIPTOR)

Use the `TypeName()` method to retrieve the protobuf type name of an inner message.

### Timestamp

Timestamp messages can be converted to/from RFC 3339 date string format (JSON string) using the `ToJsonString()`/`FromJsonString()` methods. For example:

    timestamp_message.FromJsonString("1970-01-01T00:00:00Z")
    assert timestamp_message.ToJsonString() == "1970-01-01T00:00:00Z"

You can also call `GetCurrentTime()` to fill the Timestamp message with current time:

    timestamp_message.GetCurrentTime()

To convert between other time units since epoch, you can call `ToNanoseconds(), FromNanoseconds(), ToMicroseconds(), FromMicroseconds(), ToMilliseconds(), FromMilliseconds(), ToSeconds()`, or `FromSeconds()`. The generated code also has `ToDatetime()` and `FromDatetime()` methods to convert between Python datetime objects and Timestamps. For example:

    timestamp_message.FromMicroseconds(-1)
    assert timestamp_message.ToMicroseconds() == -1
    dt = datetime(2016, 1, 1)
    timestamp_message.FromDatetime(dt)
    self.assertEqual(dt, timestamp_message.ToDatetime())

### Duration

Duration messages have the same methods as Timestamp to convert between JSON string and other time units. To convert between timedelta and Duration, you can call `ToTimedelta()` or `FromTimedelta`. For example:

    duration_message.FromNanoseconds(1999999999)
    td = duration_message.ToTimedelta()
    assert td.seconds == 1
    assert td.microseconds == 999999

### FieldMask

FieldMask messages can be converted to/from JSON string using the `ToJsonString()`/`FromJsonString()` methods. In addition, a FieldMask message has the following methods:

  * `IsValidForDescriptor(message_descriptor)`: Checks whether the FieldMask is valid for Message Descriptor.
  * `AllFieldsFromDescriptor(message_descriptor)`: Gets all direct fields of Message Descriptor to FieldMask.
  * `CanonicalFormFromMask(mask)`: Converts a FieldMask to the canonical form.
  * `Union(mask1, mask2)`: Merges two FieldMasks into this FieldMask.
  * `Intersect(mask1, mask2)`: Intersects two FieldMasks into this FieldMask.
  * `MergeMessage(source, destination, replace_message_field=False, replace_repeated_field=False)`: Merges fields specified in FieldMask from source to destination.

### Struct

Struct messages let you get and set the items directly. For example:

    struct_message["key1"] = 5
    struct_message["key2"] = "abc"
    struct_message["key3"] = True

To get or create a list/struct, you can call `get_or_create_list()`/`get_or_create_struct()`. For example:

    struct.get_or_create_struct("key4")["subkey"] = 11.0
    struct.get_or_create_list("key5")

### ListValue

A ListValue message acts like a Python sequence that lets you do the following:

    list_value = struct_message.get_or_create_list("key")
    list_value.extend([6, "seven", True, None])
    list_value.append(False)
    assert len(list_value) == 5
    assert list_value[0] == 6
    assert list_value[1] == "seven"
    assert list_value[2] == True
    assert list_value[3] == None
    assert list_Value[4] == False

To add a ListValue/Struct, call `add_list()`/`add_struct()`. For example:

    list_value.add_struct()["key"] = 1
    list_value.add_list().extend([1, "two", True])

## Fields

For each field in a message type, the corresponding class has a property with the same name as the field. How you can manipulate the property depends on its type.

As well as a property, the compiler generates an integer constant for each field containing its field number. The constant name is the field name converted to upper-case followed by `_FIELD_NUMBER`. For example, given the field `int32 foo_bar = 5;`, the compiler will generate the constant `FOO_BAR_FIELD_NUMBER = 5`.

If the field’s name is a Python keyword, then its property will only be accessible via `getattr()` and `setattr()`, as described in the Names that conflict with Python keywords section.

Protocol buffers defines two modes of field presence: `explicit` and `implicit`. Each of these is described in the following sections.

### Singular Fields with Explicit Presence

Singular fields with `explicit` presence are always able to differentiate between the field being unset and the field being set to its default value.

If you have a singular field `foo` of any non-message type, you can manipulate the field `foo` as if it were a regular field. For example, if `foo`’s type is `int32`, you can say:

    message.foo = 123
    print(message.foo)

Note that setting `foo` to a value of the wrong type will raise a `TypeError`.

If `foo` is read when it is not set, its value is the default value for that field. To check if `foo` is set, or to clear the value of `foo`, you must call the `HasField()` or `ClearField()` methods of the [`Message`](https://googleapis.dev/python/protobuf/latest/google/protobuf/message.html#google.protobuf.message.Message) interface. For example:

    assert not message.HasField("foo")
    message.foo = 123
    assert message.HasField("foo")
    message.ClearField("foo")
    assert not message.HasField("foo")

In Editions, fields have `explicit` presence by default. The following is an example of an `explicit` field in an Editions `.proto` file:

    edition = "2023";
    message MyMessage {
      int32 foo = 1;

### Singular Fields with Implicit Presence

Singular fields with `implicit` presence do not have a `HasField()` method. An `implicit` field is always “set” and reading the field will always return a value. Reading an `implicit` field that has not been assigned a value will return the default value for that type.

If you have a singular field `foo` of any non-message type, you can manipulate the field `foo` as if it were a regular field. For example, if `foo`’s type is `int32`, you can say:

    message.foo = 123
    print(message.foo)

Note that setting `foo` to a value of the wrong type will raise a `TypeError`.

If `foo` is read when it is not set, its value is the default value for that field. To clear the value of `foo` and reset it to the default value for its type, you call the `ClearField()` method of the [`Message`](https://googleapis.dev/python/protobuf/latest/google/protobuf/message.html#google.protobuf.message.Message) interface. For example:

    message.foo = 123
    message.ClearField("foo")

### Singular Message Fields

Message types work slightly differently. You cannot assign a value to an embedded message field. Instead, assigning a value to any field within the child message implies setting the message field in the parent. Submessages always have explicit presence, so you can also use the parent message’s `HasField()` method to check if a message type field value has been set.

So, for example, let’s say you have the following `.proto` definition:

    edition = "2023";
    message Foo {
      Bar bar = 1;
    message Bar {
      int32 i = 1;

You _cannot_ do the following:

    foo = Foo()
    foo.bar = Bar()  # WRONG!

Instead, to set `bar`, you simply assign a value directly to a field within `bar`, and - presto! - `foo` has a `bar` field:

    foo = Foo()
    assert not foo.HasField("bar")
    foo.bar.i = 1
    assert foo.HasField("bar")
    assert foo.bar.i == 1
    foo.ClearField("bar")
    assert not foo.HasField("bar")
    assert foo.bar.i == 0  # Default value

Similarly, you can set `bar` using the [`Message`](https://googleapis.dev/python/protobuf/latest/google/protobuf/message.html#google.protobuf.message.Message) interface’s `CopyFrom()` method. This copies all the values from another message of the same type as `bar`.

    foo.bar.CopyFrom(baz)

Note that simply reading a field inside `bar` does _not_ set the field:

    foo = Foo()
    assert not foo.HasField("bar")
    print(foo.bar.i)  # Print i's default value
    assert not foo.HasField("bar")

If you need the "has" bit on a message that does not have any fields you can or want to set, you may use the `SetInParent()` method.

    foo = Foo()
    assert not foo.HasField("bar")
    foo.bar.SetInParent()  # Set Foo.bar to a default Bar message
    assert foo.HasField("bar")

### Repeated Fields

There are three types of repeated fields: scalar, enum, and message. Map fields and oneof fields cannot be repeated.

### Repeated Scalar and Enum Fields

Repeated fields are represented as an object that acts like a Python sequence. As with embedded messages, you cannot assign the field directly, but you can manipulate it. For example, given this message definition:

    message Foo {
      repeated int32 nums = 1;

You can do the following:

    foo = Foo()
    foo.nums.append(15)        # Appends one value
    foo.nums.extend([32, 47])  # Appends an entire list

    assert len(foo.nums) == 3
    assert foo.nums[0] == 15
    assert foo.nums[1] == 32
    assert foo.nums == [15, 32, 47]

    foo.nums[:] = [33, 48]     # Assigns an entire list
    assert foo.nums == [33, 48]

    foo.nums[1] = 56    # Reassigns a value
    assert foo.nums[1] == 56
    for i in foo.nums:  # Loops and print
      print(i)
    del foo.nums[:]     # Clears list (works just like in a Python list)

The `ClearField()` method of the [`Message`](https://googleapis.dev/python/protobuf/latest/google/protobuf/message.html#google.protobuf.message.Message) interface works in addition to using Python `del`.

When using the index to retrieve a value, you can use negative numbers, such as using `-1` to retrieve the last element in the list. If your index goes out of bounds, you’ll get an `IndexError: list index out of range`.

### Repeated Message Fields

Repeated message fields work similar to repeated scalar fields. However, the corresponding Python object also has an `add()` method that creates a new message object, appends it to the list, and returns it for the caller to fill in. Also, the object’s `append()` method makes a **copy** of the given message and appends that copy to the list. This is done so that messages are always owned by the parent message to avoid circular references and other confusion that can happen when a mutable data structure has multiple owners. Similarly, the object’s `extend()` method appends an entire list of messages, but makes a **copy** of every message in the list.

For example, given this message definition:

    edition = "2023";
    message Foo {
      repeated Bar bars = 1;
    message Bar {
      int32 i = 1;
      int32 j = 2;

You can do the following:

    foo = Foo()
    bar = foo.bars.add()        # Adds a Bar then modify
    bar.i = 15
    foo.bars.add().i = 32       # Adds and modify at the same time
    new_bar = Bar()
    new_bar.i = 40
    another_bar = Bar()
    another_bar.i = 57
    foo.bars.append(new_bar)        # Uses append() to copy
    foo.bars.extend([another_bar])  # Uses extend() to copy

    assert len(foo.bars) == 4
    assert foo.bars[0].i == 15
    assert foo.bars[1].i == 32
    assert foo.bars[2].i == 40
    assert foo.bars[2] == new_bar      # The appended message is equal,
    assert foo.bars[2] is not new_bar  # but it is a copy!
    assert foo.bars[3].i == 57
    assert foo.bars[3] == another_bar      # The extended message is equal,
    assert foo.bars[3] is not another_bar  # but it is a copy!

    foo.bars[1].i = 56    # Modifies a single element
    assert foo.bars[1].i == 56
    for bar in foo.bars:  # Loops and print
      print(bar.i)
    del foo.bars[:]       # Clears list

    # add() also forwards keyword arguments to the concrete class.
    # For example, you can do:

    foo.bars.add(i=12, j=13)

    # Initializers forward keyword arguments to a concrete class too.
    # For example:

    foo = Foo(             # Creates Foo
      bars=[               # with its field bars set to a list
        Bar(i=15, j=17),   # where each list member is also initialized during creation.
        Bar(i=32),
        Bar(i=47, j=77),
    )

    assert len(foo.bars) == 3
    assert foo.bars[0].i == 15
    assert foo.bars[0].j == 17
    assert foo.bars[1].i == 32
    assert foo.bars[2].i == 47
    assert foo.bars[2].j == 77

Unlike repeated scalar fields, repeated message fields **don’t** support item assignment (i.e. [`__setitem__`](https://docs.python.org/3/reference/datamodel#object.__setitem__)). For example:

    foo = Foo()
    foo.bars.add(i=3)
    # WRONG!
    foo.bars[0] = Bar(i=15)  # Raises an exception
    # WRONG!
    foo.bars[:] = [Bar(i=15), Bar(i=17)]  # Also raises an exception
    # WRONG!
    # AttributeError: Cannot delete field attribute
    del foo.bars
    # RIGHT
    del foo.bars[:]
    foo.bars.extend([Bar(i=15), Bar(i=17)])

### Groups (proto2)

**Note that groups are deprecated and should not be used when creating new message types – use nested message types (proto2, proto3) or [delimited fields](https://protobuf.dev/editions/features#message_encoding) (editions) instead.**

A group combines a nested message type and a field into a single declaration, and uses a different [wire format](https://protobuf.dev/programming-guides/encoding) for the message. The generated message has the same name as the group. The generated field’s name is the **lowercased** name of the group.

For example, except for wire format, the following two message definitions are equivalent:

    // Version 1: Using groups
    message SearchResponse {
      repeated group SearchResult = 1 {
        optional string url = 1;
    // Version 2: Not using groups
    message SearchResponse {
      message SearchResult {
        optional string url = 1;
      repeated SearchResult searchresult = 1;

A group is either `required`, `optional`, or `repeated`. A required or optional group is manipulated using the same API as a regular singular message field. A repeated group is manipulated using the same API as a regular repeated message field.

For example, given the above `SearchResponse` definition, you can do the following:

    resp = SearchResponse()
    resp.searchresult.add(url="https://blog.google")
    assert resp.searchresult[0].url == "https://blog.google"
    assert resp.searchresult[0] == SearchResponse.SearchResult(url="https://blog.google")

### Map Fields

Given this message definition:

    message MyMessage {
      map<int32, int32> mapfield = 1;

The generated Python API for the map field is just like a Python `dict`:

    # Assign value to map
    m.mapfield[5] = 10

    # Read value from map
    m.mapfield[5]

    # Iterate over map keys
    for key in m.mapfield:
      print(key)
      print(m.mapfield[key])

    # Test whether key is in map:
    if 5 in m.mapfield:
      print(“Found!”)

    # Delete key from map.
    del m.mapfield[key]

As with embedded message fields, messages cannot be directly assigned into a map value. Instead, to add a message as a map value you reference an undefined key, which constructs and returns a new submessage:

    m.message_map[key].submessage_field = 10

You can find out more about undefined keys in the next section.

#### Referencing undefined keys

The semantics of Protocol Buffer maps behave slightly differently to Python `dict`s when it comes to undefined keys. In a regular Python `dict`, referencing an undefined key raises a KeyError exception:

    >>> x = {}
    >>> x[5]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 5

However, in Protocol Buffers maps, referencing an undefined key creates the key in the map with a zero/false/empty value. This behavior is more like the Python standard library `defaultdict`.

    >>> dict(m.mapfield)
    >>> m.mapfield[5]
    0
    >>> dict(m.mapfield)
    {5: 0}

This behavior is especially convenient for maps with message type values, because you can directly update the fields of the returned message.

    >>> m.message_map[5].foo = 3

Note that even if you don’t assign any values to message fields, the submessage is still created in the map:

    >>> m.message_map[10]
    <test_pb2.M2 object at 0x7fb022af28c0>
    >>> dict(m.message_map)
    {10: <test_pb2.M2 object at 0x7fb022af28c0>}

This is **different** from regular embedded message fields, where the message itself is only created once you assign a value to one of its fields.

As it may not be immediately obvious to anyone reading your code that `m.message_map[10]` alone, for example, may create a submessage, we also provide a `get_or_create()` method that does the same thing but whose name makes the possible message creation more explicit:

    # Equivalent to:
    #   m.message_map[10]
    # but more explicit that the statement might be creating a new
    # empty message in the map.
    m.message_map.get_or_create(10)

### Memory management

Note that clearing a field (via `ClearField`, `Clear`, `del` (for lists) or `ClearExtension`) doesn’t necessarily reclaim memory. It just resets the object to look as if things are unset, but the subobjects _may_ continue to exist. For example, clearing a repeated field sets its size to 0, but does not relinquish its capacity (analogous to calling `.clear()` on a `std::vector` in C++).

There are various ways in which to ensure the memory is freed up. One method is to make a copy of the proto after clearing the fields, as the unused memory is not copied over:

    # Assuming 'my_proto' has a memory-intensive field 'big_field'
    # Clears the field. Memory might still be reserved.
    my_proto.ClearField('big_field')

    # Copy to a new instance. This allocates only necessary memory.
    compact_proto = my_proto_pb2.MyProto()
    compact_proto.CopyFrom(my_proto)

    # Once all references to the initial proto are gone, it is garbage collected.
    my_proto = compact_proto

## Enumerations

In Python, enums are just integers. A set of integral constants are defined corresponding to the enum’s defined values. For example, given:

    message Foo {
      enum SomeEnum {
        VALUE_A = 0;
        VALUE_B = 5;
        VALUE_C = 1234;
      SomeEnum bar = 1;

The constants `VALUE_A`, `VALUE_B`, and `VALUE_C` are defined with values 0, 5, and 1234, respectively. You can access `SomeEnum` if desired. If an enum is defined in the outer scope, the values are module constants; if it is defined within a message (like above), they become static members of that message class.

For example, you can access the values in the three following ways for the following enum in a proto:

    enum SomeEnum {
      VALUE_A = 0;
      VALUE_B = 5;
      VALUE_C = 1234;

    value_a = myproto_pb2.SomeEnum.VALUE_A
    # or
    myproto_pb2.VALUE_A
    # or
    myproto_pb2.SomeEnum.Value('VALUE_A')

An enum field works just like a scalar field.

    foo = Foo()
    foo.bar = Foo.VALUE_A
    assert foo.bar == 0
    assert foo.bar == Foo.VALUE_A

If the enum’s name (or an enum value) is a Python keyword, then its object (or the enum value’s property) will only be accessible via `getattr()`, as described in the Names that conflict with Python keywords section.

With proto2, enums are closed, and with proto3, enums are open. In Editions, the `enum_type` feature determines the behavior of an enum.

  * `OPEN` enums can have any `int32` value, even if it is not specified in the enum definition. This is the default in Editions.
  * `CLOSED` enums cannot contain a numeric value other than those defined for the enum type. If you assign a value that is not in the enum, the generated code will throw an exception. This is equivalent to the behavior of enums in proto2.

Enums have a number of utility methods for getting field names from values and vice versa, lists of fields, and so on - these are defined in [`enum_type_wrapper.EnumTypeWrapper`](https://github.com/protocolbuffers/protobuf/blob/master/python/google/protobuf/internal/enum_type_wrapper.py) (the base class for generated enum classes). So, for example, if you have the following standalone enum in `myproto.proto`:

    enum SomeEnum {
      VALUE_A = 0;
      VALUE_B = 5;
      VALUE_C = 1234;

…you can do this:

    self.assertEqual('VALUE_A', myproto_pb2.SomeEnum.Name(myproto_pb2.VALUE_A))
    self.assertEqual(5, myproto_pb2.SomeEnum.Value('VALUE_B'))

For an enum declared within a protocol message, such as Foo above, the syntax is similar:

    self.assertEqual('VALUE_A', myproto_pb2.Foo.SomeEnum.Name(myproto_pb2.Foo.VALUE_A))
    self.assertEqual(5, myproto_pb2.Foo.SomeEnum.Value('VALUE_B'))

If multiple enum constants have the same value (aliases), the first constant defined is returned.

    enum SomeEnum {
      option allow_alias = true;
      VALUE_A = 0;
      VALUE_B = 5;
      VALUE_C = 1234;
      VALUE_B_ALIAS = 5;

In the above example, `myproto_pb2.SomeEnum.Name(5)` returns `"VALUE_B"`.

## Oneof

Given a message with a oneof:

    message Foo {
      oneof test_oneof {
         string name = 1;
         int32 serial_number = 2;

The Python class corresponding to `Foo` will have properties called `name` and `serial_number` just like regular fields. However, unlike regular fields, at most one of the fields in a oneof can be set at a time, which is ensured by the runtime. For example:

    message = Foo()
    message.name = "Bender"
    assert message.HasField("name")
    message.serial_number = 2716057
    assert message.HasField("serial_number")
    assert not message.HasField("name")

The message class also has a `WhichOneof` method that lets you find out which field (if any) in the oneof has been set. This method returns the name of the field that is set, or `None` if nothing has been set:

    assert message.WhichOneof("test_oneof") is None
    message.name = "Bender"
    assert message.WhichOneof("test_oneof") == "name"

`HasField` and `ClearField` also accept oneof names in addition to field names:

    assert not message.HasField("test_oneof")
    message.name = "Bender"
    assert message.HasField("test_oneof")
    message.serial_number = 2716057
    assert message.HasField("test_oneof")
    message.ClearField("test_oneof")
    assert not message.HasField("test_oneof")
    assert not message.HasField("serial_number")

Note that calling `ClearField` on a oneof just clears the currently set field.

## Names that conflict with Python keywords

If the name of a message, field, enum, or enum value is a [Python keyword](https://docs.python.org/3/reference/lexical_analysis#keywords), then the name of its corresponding class or property will be the same, but you’ll only be able to access it using Python’s [`getattr()`](https://docs.python.org/3/library/functions#getattr) and [`setattr()`](https://docs.python.org/3/library/functions#setattr) built-in functions, and not via Python’s normal attribute reference syntax (i.e. the dot operator).

For example, if you have the following `.proto` definition:

    message Baz {
      optional int32 from = 1
      repeated int32 in = 2;

You would access those fields like this:

    baz = Baz()
    setattr(baz, "from", 99)
    assert getattr(baz, "from") == 99
    getattr(baz, "in").append(42)
    assert getattr(baz, "in") == [42]

By contrast, trying to use `obj.attr` syntax to access these fields results in Python raising syntax errors when parsing your code:

    # WRONG!
    baz.in  # SyntaxError: invalid syntax
    baz.from  # SyntaxError: invalid syntax

## Extensions

Given a proto2 or editions message with an extension range:

    edition = "2023";
    message Foo {
      extensions 100 to 199;

The Python class corresponding to `Foo` will have a member called `Extensions`, which is a dictionary mapping extension identifiers to their current values.

Given an extension definition:

    extend Foo {
      int32 bar = 123;

The protocol buffer compiler generates an "extension identifier" called `bar`. The identifier acts as a key to the `Extensions` dictionary. The result of looking up a value in this dictionary is exactly the same as if you accessed a normal field of the same type. So, given the above example, you could do:

    foo = Foo()
    foo.Extensions[proto_file_pb2.bar] = 2
    assert foo.Extensions[proto_file_pb2.bar] == 2

Note that you need to specify the extension identifier constant, not just a string name: this is because it’s possible for multiple extensions with the same name to be specified in different scopes.

Analogous to normal fields, `Extensions[...]` returns a message object for singular messages and a sequence for repeated fields.

The [`Message`](https://googleapis.dev/python/protobuf/latest/google/protobuf/message.html#google.protobuf.message.Message) interface’s `HasField()` and `ClearField()` methods do not work with extensions; you must use `HasExtension()` and `ClearExtension()` instead. To use the `HasExtension()` and `ClearExtension()` methods, pass in the `field_descriptor` for the extension you are checking for the existence of.

## Services

If the `.proto` file contains the following line:

    option py_generic_services = true;

Then the protocol buffer compiler will generate code based on the service definitions found in the file as described in this section. However, the generated code may be undesirable as it is not tied to any particular RPC system, and thus requires more levels of indirection that code tailored to one system. If you do NOT want this code to be generated, add this line to the file:

    option py_generic_services = false;

If neither of the above lines are given, the option defaults to `false`, as generic services are deprecated. (Note that prior to 2.4.0, the option defaults to `true`)

RPC systems based on `.proto`-language service definitions should provide [plugins](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.compiler.plugin.pb) to generate code appropriate for the system. These plugins are likely to require that abstract services are disabled, so that they can generate their own classes of the same names.

The remainder of this section describes what the protocol buffer compiler generates when abstract services are enabled.

### Interface

Given a service definition:

    service Foo {
      rpc Bar(FooRequest) returns(FooResponse);

The protocol buffer compiler will generate a class `Foo` to represent this service. `Foo` will have a method for each method defined in the service definition. In this case, the method `Bar` is defined as:

    def Bar(self, rpc_controller, request, done)

The parameters are equivalent to the parameters of [`Service.CallMethod()`](https://googleapis.dev/python/protobuf/latest/google/protobuf/service.html#google.protobuf.service.Service.CallMethod), except that the `method_descriptor` argument is implied.

These generated methods are intended to be overridden by subclasses. The default implementations simply call [`controller.SetFailed()`](https://googleapis.dev/python/protobuf/latest/google/protobuf/service.html#google.protobuf.service.RpcController.SetFailed) with an error message indicating that the method is unimplemented, then invoke the `done` callback. When implementing your own service, you must subclass this generated service and implement its methods as appropriate.

`Foo` subclasses the `Service` interface. The protocol buffer compiler automatically generates implementations of the methods of `Service` as follows:

  * `GetDescriptor`: Returns the service’s [`ServiceDescriptor`](https://googleapis.dev/python/protobuf/latest/google/protobuf/descriptor.html#google.protobuf.descriptor.ServiceDescriptor).
  * `CallMethod`: Determines which method is being called based on the provided method descriptor and calls it directly.
  * `GetRequestClass` and `GetResponseClass`: Returns the class of the request or response of the correct type for the given method.

### Stub

The protocol buffer compiler also generates a "stub" implementation of every service interface, which is used by clients wishing to send requests to servers implementing the service. For the `Foo` service (above), the stub implementation `Foo_Stub` will be defined.

`Foo_Stub` is a subclass of `Foo`. Its constructor takes an [`RpcChannel`](https://googleapis.dev/python/protobuf/latest/google/protobuf/service.html#google.protobuf.service.RpcChannel) as a parameter. The stub then implements each of the service’s methods by calling the channel’s `CallMethod()` method.

The Protocol Buffer library does not include an RPC implementation. However, it includes all of the tools you need to hook up a generated service class to any arbitrary RPC implementation of your choice. You need only provide implementations of `RpcChannel` and [`RpcController`](https://googleapis.dev/python/protobuf/latest/google/protobuf/service.html#google.protobuf.service.RpcController).

## Plugin Insertion Points

[Code generator plugins](https://protobuf.dev/reference/cpp/api-docs/google.protobuf.compiler.plugin) which want to extend the output of the Python code generator may insert code of the following types using the given insertion point names.

  * `imports`: Import statements.
  * `module_scope`: Top-level declarations.

#### Warning

Do not generate code which relies on private class members declared by the standard code generator, as these implementation details may change in future versions of Protocol Buffers.

## Sharing Messages Between Python and C++

Prior to the 4.21.0 version of the Protobuf Python API, Python apps could share messages with C++ using a native extension. Starting in the 4.21.0 API version, sharing messages between Python and C++ is not supported by the default install. To enable this capability when working with the 4.x and later versions of the Protobuf Python API, define the environment variable, `PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp`, and ensure that the Python/C++ extension is installed.


# Downloads

The downloads page for protocol buffers.

## Release Packages

### Latest Version

The latest release of Protocol Buffers can be found on the [release page](https://github.com/protocolbuffers/protobuf/releases/latest).

### Old Versions

Older versions are available in our historical releases [on GitHub](https://github.com/protocolbuffers/protobuf/releases).

## Source Code

### GitHub Repository

Protocol Buffers source code is hosted on [GitHub](https://github.com/protocolbuffers/protobuf).