protoreflect

package
v1.33.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 5, 2024 License: BSD-3-Clause Imports: 9 Imported by: 82,052

Documentation

Overview

Package protoreflect provides interfaces to dynamically manipulate messages.

This package includes type descriptors which describe the structure of types defined in proto source files and value interfaces which provide the ability to examine and manipulate the contents of messages.

Protocol Buffer Descriptors

Protobuf descriptors (e.g., EnumDescriptor or MessageDescriptor) are immutable objects that represent protobuf type information. They are wrappers around the messages declared in descriptor.proto. Protobuf descriptors alone lack any information regarding Go types.

Enums and messages generated by this module implement Enum and ProtoMessage, where the Descriptor and ProtoReflect.Descriptor accessors respectively return the protobuf descriptor for the values.

The protobuf descriptor interfaces are not meant to be implemented by user code since they might need to be extended in the future to support additions to the protobuf language. The google.golang.org/protobuf/reflect/protodesc package converts between google.protobuf.DescriptorProto messages and protobuf descriptors.

Go Type Descriptors

A type descriptor (e.g., EnumType or MessageType) is a constructor for a concrete Go type that represents the associated protobuf descriptor. There is commonly a one-to-one relationship between protobuf descriptors and Go type descriptors, but it can potentially be a one-to-many relationship.

Enums and messages generated by this module implement Enum and ProtoMessage, where the Type and ProtoReflect.Type accessors respectively return the protobuf descriptor for the values.

The google.golang.org/protobuf/types/dynamicpb package can be used to create Go type descriptors from protobuf descriptors.

Value Interfaces

The Enum and Message interfaces provide a reflective view over an enum or message instance. For enums, it provides the ability to retrieve the enum value number for any concrete enum type. For messages, it provides the ability to access or manipulate fields of the message.

To convert a google.golang.org/protobuf/proto.Message to a protoreflect.Message, use the former's ProtoReflect method. Since the ProtoReflect method is new to the v2 message interface, it may not be present on older message implementations. The github.com/golang/protobuf/proto.MessageReflect function can be used to obtain a reflective view on older messages.

Relationships

The following diagrams demonstrate the relationships between various types declared in this package.

                       ┌───────────────────────────────────┐
                       V                                   │
   ┌────────────── New(n) ─────────────┐                   │
   │                                   │                   │
   │      ┌──── Descriptor() ──┐       │  ┌── Number() ──┐ │
   │      │                    V       V  │              V │
╔════════════╗  ╔════════════════╗  ╔════════╗  ╔════════════╗
║  EnumType  ║  ║ EnumDescriptor ║  ║  Enum  ║  ║ EnumNumber ║
╚════════════╝  ╚════════════════╝  ╚════════╝  ╚════════════╝
      Λ           Λ                   │ │
      │           └─── Descriptor() ──┘ │
      │                                 │
      └────────────────── Type() ───────┘

• An EnumType describes a concrete Go enum type. It has an EnumDescriptor and can construct an Enum instance.

• An EnumDescriptor describes an abstract protobuf enum type.

• An Enum is a concrete enum instance. Generated enums implement Enum.

  ┌──────────────── New() ─────────────────┐
  │                                        │
  │         ┌─── Descriptor() ─────┐       │   ┌── Interface() ───┐
  │         │                      V       V   │                  V
╔═════════════╗  ╔═══════════════════╗  ╔═════════╗  ╔══════════════╗
║ MessageType ║  ║ MessageDescriptor ║  ║ Message ║  ║ ProtoMessage ║
╚═════════════╝  ╚═══════════════════╝  ╚═════════╝  ╚══════════════╝
       Λ           Λ                      │ │  Λ                  │
       │           └──── Descriptor() ────┘ │  └─ ProtoReflect() ─┘
       │                                    │
       └─────────────────── Type() ─────────┘

• A MessageType describes a concrete Go message type. It has a MessageDescriptor and can construct a Message instance. Just as how Go's reflect.Type is a reflective description of a Go type, a MessageType is a reflective description of a Go type for a protobuf message.

• A MessageDescriptor describes an abstract protobuf message type. It has no understanding of Go types. In order to construct a MessageType from just a MessageDescriptor, you can consider looking up the message type in the global registry using the FindMessageByName method on google.golang.org/protobuf/reflect/protoregistry.GlobalTypes or constructing a dynamic MessageType using google.golang.org/protobuf/types/dynamicpb.NewMessageType.

• A Message is a reflective view over a concrete message instance. Generated messages implement ProtoMessage, which can convert to a Message. Just as how Go's reflect.Value is a reflective view over a Go value, a Message is a reflective view over a concrete protobuf message instance. Using Go reflection as an analogy, the [ProtoMessage.ProtoReflect] method is similar to calling reflect.ValueOf, and the [Message.Interface] method is similar to calling reflect.Value.Interface.

      ┌── TypeDescriptor() ──┐    ┌───── Descriptor() ─────┐
      │                      V    │                        V
╔═══════════════╗  ╔═════════════════════════╗  ╔═════════════════════╗
║ ExtensionType ║  ║ ExtensionTypeDescriptor ║  ║ ExtensionDescriptor ║
╚═══════════════╝  ╚═════════════════════════╝  ╚═════════════════════╝
      Λ                      │   │ Λ                      │ Λ
      └─────── Type() ───────┘   │ └─── may implement ────┘ │
                                 │                          │
                                 └────── implements ────────┘

• An ExtensionType describes a concrete Go implementation of an extension. It has an ExtensionTypeDescriptor and can convert to/from an abstract Value and a Go value.

• An ExtensionTypeDescriptor is an ExtensionDescriptor which also has an ExtensionType.

• An ExtensionDescriptor describes an abstract protobuf extension field and may not always be an ExtensionTypeDescriptor.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cardinality

type Cardinality cardinality

Cardinality determines whether a field is optional, required, or repeated.

const (
	Optional Cardinality = 1 // appears zero or one times
	Required Cardinality = 2 // appears exactly one time; invalid with Proto3
	Repeated Cardinality = 3 // appears zero or more times
)

Constants as defined by the google.protobuf.Cardinality enumeration.

func (Cardinality) GoString

func (c Cardinality) GoString() string

GoString returns c as a Go source identifier (e.g., "Optional").

func (Cardinality) IsValid

func (c Cardinality) IsValid() bool

IsValid reports whether the cardinality is valid.

func (Cardinality) String

func (c Cardinality) String() string

String returns c as a proto source identifier (e.g., "optional").

type Descriptor

type Descriptor interface {
	// ParentFile returns the parent file descriptor that this descriptor
	// is declared within. The parent file for the file descriptor is itself.
	//
	// Support for this functionality is optional and may return nil.
	ParentFile() FileDescriptor

	// Parent returns the parent containing this descriptor declaration.
	// The following shows the mapping from child type to possible parent types:
	//
	//	╔═════════════════════╤═══════════════════════════════════╗
	//	║ Child type          │ Possible parent types             ║
	//	╠═════════════════════╪═══════════════════════════════════╣
	//	║ FileDescriptor      │ nil                               ║
	//	║ MessageDescriptor   │ FileDescriptor, MessageDescriptor ║
	//	║ FieldDescriptor     │ FileDescriptor, MessageDescriptor ║
	//	║ OneofDescriptor     │ MessageDescriptor                 ║
	//	║ EnumDescriptor      │ FileDescriptor, MessageDescriptor ║
	//	║ EnumValueDescriptor │ EnumDescriptor                    ║
	//	║ ServiceDescriptor   │ FileDescriptor                    ║
	//	║ MethodDescriptor    │ ServiceDescriptor                 ║
	//	╚═════════════════════╧═══════════════════════════════════╝
	//
	// Support for this functionality is optional and may return nil.
	Parent() Descriptor

	// Index returns the index of this descriptor within its parent.
	// It returns 0 if the descriptor does not have a parent or if the parent
	// is unknown.
	Index() int

	// Syntax is the protobuf syntax.
	Syntax() Syntax // e.g., Proto2 or Proto3

	// Name is the short name of the declaration (i.e., FullName.Name).
	Name() Name // e.g., "Any"

	// FullName is the fully-qualified name of the declaration.
	//
	// The FullName is a concatenation of the full name of the type that this
	// type is declared within and the declaration name. For example,
	// field "foo_field" in message "proto.package.MyMessage" is
	// uniquely identified as "proto.package.MyMessage.foo_field".
	// Enum values are an exception to the rule (see EnumValueDescriptor).
	FullName() FullName // e.g., "google.protobuf.Any"

	// IsPlaceholder reports whether type information is missing since a
	// dependency is not resolved, in which case only name information is known.
	//
	// Placeholder types may only be returned by the following accessors
	// as a result of unresolved dependencies or weak imports:
	//
	//	╔═══════════════════════════════════╤═════════════════════╗
	//	║ Accessor                          │ Descriptor          ║
	//	╠═══════════════════════════════════╪═════════════════════╣
	//	║ FileImports.FileDescriptor        │ FileDescriptor      ║
	//	║ FieldDescriptor.Enum              │ EnumDescriptor      ║
	//	║ FieldDescriptor.Message           │ MessageDescriptor   ║
	//	║ FieldDescriptor.DefaultEnumValue  │ EnumValueDescriptor ║
	//	║ FieldDescriptor.ContainingMessage │ MessageDescriptor   ║
	//	║ MethodDescriptor.Input            │ MessageDescriptor   ║
	//	║ MethodDescriptor.Output           │ MessageDescriptor   ║
	//	╚═══════════════════════════════════╧═════════════════════╝
	//
	// If true, only Name and FullName are valid.
	// For FileDescriptor, the Path is also valid.
	IsPlaceholder() bool

	// Options returns the descriptor options. The caller must not modify
	// the returned value.
	//
	// To avoid a dependency cycle, this function returns a proto.Message value.
	// The proto message type returned for each descriptor type is as follows:
	//	╔═════════════════════╤══════════════════════════════════════════╗
	//	║ Go type             │ Protobuf message type                    ║
	//	╠═════════════════════╪══════════════════════════════════════════╣
	//	║ FileDescriptor      │ google.protobuf.FileOptions              ║
	//	║ EnumDescriptor      │ google.protobuf.EnumOptions              ║
	//	║ EnumValueDescriptor │ google.protobuf.EnumValueOptions         ║
	//	║ MessageDescriptor   │ google.protobuf.MessageOptions           ║
	//	║ FieldDescriptor     │ google.protobuf.FieldOptions             ║
	//	║ OneofDescriptor     │ google.protobuf.OneofOptions             ║
	//	║ ServiceDescriptor   │ google.protobuf.ServiceOptions           ║
	//	║ MethodDescriptor    │ google.protobuf.MethodOptions            ║
	//	╚═════════════════════╧══════════════════════════════════════════╝
	//
	// This method returns a typed nil-pointer if no options are present.
	// The caller must import the descriptorpb package to use this.
	Options() ProtoMessage
	// contains filtered or unexported methods
}

Descriptor provides a set of accessors that are common to every descriptor. Each descriptor type wraps the equivalent google.protobuf.XXXDescriptorProto, but provides efficient lookup and immutability.

Each descriptor is comparable. Equality implies that the two types are exactly identical. However, it is possible for the same semantically identical proto type to be represented by multiple type descriptors.

For example, suppose we have t1 and t2 which are both an MessageDescriptor. If t1 == t2, then the types are definitely equal and all accessors return the same information. However, if t1 != t2, then it is still possible that they still represent the same proto type (e.g., t1.FullName == t2.FullName). This can occur if a descriptor type is created dynamically, or multiple versions of the same proto type are accidentally linked into the Go binary.

type Enum

type Enum interface {
	// Descriptor returns enum descriptor, which contains only the protobuf
	// type information for the enum.
	Descriptor() EnumDescriptor

	// Type returns the enum type, which encapsulates both Go and protobuf
	// type information. If the Go type information is not needed,
	// it is recommended that the enum descriptor be used instead.
	Type() EnumType

	// Number returns the enum value as an integer.
	Number() EnumNumber
}

Enum is a reflection interface for a concrete enum value, which provides type information and a getter for the enum number. Enum does not provide a mutable API since enums are commonly backed by Go constants, which are not addressable.

type EnumDescriptor

type EnumDescriptor interface {
	Descriptor

	// Values is a list of nested enum value declarations.
	Values() EnumValueDescriptors

	// ReservedNames is a list of reserved enum names.
	ReservedNames() Names
	// ReservedRanges is a list of reserved ranges of enum numbers.
	ReservedRanges() EnumRanges
	// contains filtered or unexported methods
}

EnumDescriptor describes an enum and corresponds with the google.protobuf.EnumDescriptorProto message.

Nested declarations: EnumValueDescriptor.

type EnumDescriptors

type EnumDescriptors interface {
	// Len reports the number of enum types.
	Len() int
	// Get returns the ith EnumDescriptor. It panics if out of bounds.
	Get(i int) EnumDescriptor
	// ByName returns the EnumDescriptor for an enum named s.
	// It returns nil if not found.
	ByName(s Name) EnumDescriptor
	// contains filtered or unexported methods
}

EnumDescriptors is a list of enum declarations.

type EnumNumber

type EnumNumber int32

EnumNumber is the numeric value for an enum.

type EnumRanges

type EnumRanges interface {
	// Len reports the number of ranges in the list.
	Len() int
	// Get returns the ith range. It panics if out of bounds.
	Get(i int) [2]EnumNumber // start inclusive; end inclusive
	// Has reports whether n is within any of the ranges.
	Has(n EnumNumber) bool
	// contains filtered or unexported methods
}

EnumRanges represent a list of enum number ranges.

type EnumType

type EnumType interface {
	// New returns an instance of this enum type with its value set to n.
	New(n EnumNumber) Enum

	// Descriptor returns the enum descriptor.
	//
	// Invariant: t.Descriptor() == t.New(0).Descriptor()
	Descriptor() EnumDescriptor
}

EnumType encapsulates an EnumDescriptor with a concrete Go implementation.

type EnumValueDescriptor

type EnumValueDescriptor interface {
	Descriptor

	// Number returns the enum value as an integer.
	Number() EnumNumber
	// contains filtered or unexported methods
}

EnumValueDescriptor describes an enum value and corresponds with the google.protobuf.EnumValueDescriptorProto message.

All other proto declarations are in the namespace of the parent. However, enum values do not follow this rule and are within the namespace of the parent's parent (i.e., they are a sibling of the containing enum). Thus, a value named "FOO_VALUE" declared within an enum uniquely identified as "proto.package.MyEnum" has a full name of "proto.package.FOO_VALUE".

type EnumValueDescriptors

type EnumValueDescriptors interface {
	// Len reports the number of enum values.
	Len() int
	// Get returns the ith EnumValueDescriptor. It panics if out of bounds.
	Get(i int) EnumValueDescriptor
	// ByName returns the EnumValueDescriptor for the enum value named s.
	// It returns nil if not found.
	ByName(s Name) EnumValueDescriptor
	// ByNumber returns the EnumValueDescriptor for the enum value numbered n.
	// If multiple have the same number, the first one defined is returned
	// It returns nil if not found.
	ByNumber(n EnumNumber) EnumValueDescriptor
	// contains filtered or unexported methods
}

EnumValueDescriptors is a list of enum value declarations.

type ExtensionDescriptor

type ExtensionDescriptor = FieldDescriptor

ExtensionDescriptor is an alias of FieldDescriptor for documentation.

type ExtensionDescriptors

type ExtensionDescriptors interface {
	// Len reports the number of fields.
	Len() int
	// Get returns the ith ExtensionDescriptor. It panics if out of bounds.
	Get(i int) ExtensionDescriptor
	// ByName returns the ExtensionDescriptor for a field named s.
	// It returns nil if not found.
	ByName(s Name) ExtensionDescriptor
	// contains filtered or unexported methods
}

ExtensionDescriptors is a list of field declarations.

type ExtensionType

type ExtensionType interface {
	// New returns a new value for the field.
	// For scalars, this returns the default value in native Go form.
	New() Value

	// Zero returns a new value for the field.
	// For scalars, this returns the default value in native Go form.
	// For composite types, this returns an empty, read-only message, list, or map.
	Zero() Value

	// TypeDescriptor returns the extension type descriptor.
	TypeDescriptor() ExtensionTypeDescriptor

	// ValueOf wraps the input and returns it as a Value.
	// ValueOf panics if the input value is invalid or not the appropriate type.
	//
	// ValueOf is more extensive than protoreflect.ValueOf for a given field's
	// value as it has more type information available.
	ValueOf(interface{}) Value

	// InterfaceOf completely unwraps the Value to the underlying Go type.
	// InterfaceOf panics if the input is nil or does not represent the
	// appropriate underlying Go type. For composite types, it panics if the
	// value is not mutable.
	//
	// InterfaceOf is able to unwrap the Value further than Value.Interface
	// as it has more type information available.
	InterfaceOf(Value) interface{}

	// IsValidValue reports whether the Value is valid to assign to the field.
	IsValidValue(Value) bool

	// IsValidInterface reports whether the input is valid to assign to the field.
	IsValidInterface(interface{}) bool
}

ExtensionType encapsulates an ExtensionDescriptor with a concrete Go implementation. The nested field descriptor must be for a extension field.

While a normal field is a member of the parent message that it is declared within (see [Descriptor.Parent]), an extension field is a member of some other target message (see [FieldDescriptor.ContainingMessage]) and may have no relationship with the parent. However, the full name of an extension field is relative to the parent that it is declared within.

For example:

syntax = "proto2";
package example;
message FooMessage {
	extensions 100 to max;
}
message BarMessage {
	extends FooMessage { optional BarMessage bar_field = 100; }
}

Field "bar_field" is an extension of FooMessage, but its full name is "example.BarMessage.bar_field" instead of "example.FooMessage.bar_field".

type ExtensionTypeDescriptor

type ExtensionTypeDescriptor interface {
	ExtensionDescriptor

	// Type returns the associated ExtensionType.
	Type() ExtensionType

	// Descriptor returns the plain ExtensionDescriptor without the
	// associated ExtensionType.
	Descriptor() ExtensionDescriptor
}

ExtensionTypeDescriptor is an ExtensionDescriptor with an associated ExtensionType.

type FieldDescriptor

type FieldDescriptor interface {
	Descriptor

	// Number reports the unique number for this field.
	Number() FieldNumber
	// Cardinality reports the cardinality for this field.
	Cardinality() Cardinality
	// Kind reports the basic kind for this field.
	Kind() Kind

	// HasJSONName reports whether this field has an explicitly set JSON name.
	HasJSONName() bool

	// JSONName reports the name used for JSON serialization.
	// It is usually the camel-cased form of the field name.
	// Extension fields are represented by the full name surrounded by brackets.
	JSONName() string

	// TextName reports the name used for text serialization.
	// It is usually the name of the field, except that groups use the name
	// of the inlined message, and extension fields are represented by the
	// full name surrounded by brackets.
	TextName() string

	// HasPresence reports whether the field distinguishes between unpopulated
	// and default values.
	HasPresence() bool

	// IsExtension reports whether this is an extension field. If false,
	// then Parent and ContainingMessage refer to the same message.
	// Otherwise, ContainingMessage and Parent likely differ.
	IsExtension() bool

	// HasOptionalKeyword reports whether the "optional" keyword was explicitly
	// specified in the source .proto file.
	HasOptionalKeyword() bool

	// IsWeak reports whether this is a weak field, which does not impose a
	// direct dependency on the target type.
	// If true, then Message returns a placeholder type.
	IsWeak() bool

	// IsPacked reports whether repeated primitive numeric kinds should be
	// serialized using a packed encoding.
	// If true, then it implies Cardinality is Repeated.
	IsPacked() bool

	// IsList reports whether this field represents a list,
	// where the value type for the associated field is a List.
	// It is equivalent to checking whether Cardinality is Repeated and
	// that IsMap reports false.
	IsList() bool

	// IsMap reports whether this field represents a map,
	// where the value type for the associated field is a Map.
	// It is equivalent to checking whether Cardinality is Repeated,
	// that the Kind is MessageKind, and that MessageDescriptor.IsMapEntry reports true.
	IsMap() bool

	// MapKey returns the field descriptor for the key in the map entry.
	// It returns nil if IsMap reports false.
	MapKey() FieldDescriptor

	// MapValue returns the field descriptor for the value in the map entry.
	// It returns nil if IsMap reports false.
	MapValue() FieldDescriptor

	// HasDefault reports whether this field has a default value.
	HasDefault() bool

	// Default returns the default value for scalar fields.
	// For proto2, it is the default value as specified in the proto file,
	// or the zero value if unspecified.
	// For proto3, it is always the zero value of the scalar.
	// The Value type is determined by the Kind.
	Default() Value

	// DefaultEnumValue returns the enum value descriptor for the default value
	// of an enum field, and is nil for any other kind of field.
	DefaultEnumValue() EnumValueDescriptor

	// ContainingOneof is the containing oneof that this field belongs to,
	// and is nil if this field is not part of a oneof.
	ContainingOneof() OneofDescriptor

	// ContainingMessage is the containing message that this field belongs to.
	// For extension fields, this may not necessarily be the parent message
	// that the field is declared within.
	ContainingMessage() MessageDescriptor

	// Enum is the enum descriptor if Kind is EnumKind.
	// It returns nil for any other Kind.
	Enum() EnumDescriptor

	// Message is the message descriptor if Kind is
	// MessageKind or GroupKind. It returns nil for any other Kind.
	Message() MessageDescriptor
	// contains filtered or unexported methods
}

FieldDescriptor describes a field within a message and corresponds with the google.protobuf.FieldDescriptorProto message.

It is used for both normal fields defined within the parent message (e.g., [MessageDescriptor.Fields]) and fields that extend some remote message (e.g., [FileDescriptor.Extensions] or [MessageDescriptor.Extensions]).

type FieldDescriptors

type FieldDescriptors interface {
	// Len reports the number of fields.
	Len() int
	// Get returns the ith FieldDescriptor. It panics if out of bounds.
	Get(i int) FieldDescriptor
	// ByName returns the FieldDescriptor for a field named s.
	// It returns nil if not found.
	ByName(s Name) FieldDescriptor
	// ByJSONName returns the FieldDescriptor for a field with s as the JSON name.
	// It returns nil if not found.
	ByJSONName(s string) FieldDescriptor
	// ByTextName returns the FieldDescriptor for a field with s as the text name.
	// It returns nil if not found.
	ByTextName(s string) FieldDescriptor
	// ByNumber returns the FieldDescriptor for a field numbered n.
	// It returns nil if not found.
	ByNumber(n FieldNumber) FieldDescriptor
	// contains filtered or unexported methods
}

FieldDescriptors is a list of field declarations.

type FieldNumber

type FieldNumber = protowire.Number

FieldNumber is the field number in a message.

type FieldNumbers

type FieldNumbers interface {
	// Len reports the number of fields in the list.
	Len() int
	// Get returns the ith field number. It panics if out of bounds.
	Get(i int) FieldNumber
	// Has reports whether n is within the list of fields.
	Has(n FieldNumber) bool
	// contains filtered or unexported methods
}

FieldNumbers represent a list of field numbers.

type FieldRanges

type FieldRanges interface {
	// Len reports the number of ranges in the list.
	Len() int
	// Get returns the ith range. It panics if out of bounds.
	Get(i int) [2]FieldNumber // start inclusive; end exclusive
	// Has reports whether n is within any of the ranges.
	Has(n FieldNumber) bool
	// contains filtered or unexported methods
}

FieldRanges represent a list of field number ranges.

type FileDescriptor

type FileDescriptor interface {
	Descriptor // Descriptor.FullName is identical to Package

	// Path returns the file name, relative to the source tree root.
	Path() string // e.g., "path/to/file.proto"
	// Package returns the protobuf package namespace.
	Package() FullName // e.g., "google.protobuf"

	// Imports is a list of imported proto files.
	Imports() FileImports

	// Enums is a list of the top-level enum declarations.
	Enums() EnumDescriptors
	// Messages is a list of the top-level message declarations.
	Messages() MessageDescriptors
	// Extensions is a list of the top-level extension declarations.
	Extensions() ExtensionDescriptors
	// Services is a list of the top-level service declarations.
	Services() ServiceDescriptors

	// SourceLocations is a list of source locations.
	SourceLocations() SourceLocations
	// contains filtered or unexported methods
}

FileDescriptor describes the types in a complete proto file and corresponds with the google.protobuf.FileDescriptorProto message.

Top-level declarations: EnumDescriptor, MessageDescriptor, FieldDescriptor, and/or ServiceDescriptor.

type FileImport

type FileImport struct {
	// FileDescriptor is the file type for the given import.
	// It is a placeholder descriptor if IsWeak is set or if a dependency has
	// not been regenerated to implement the new reflection APIs.
	FileDescriptor

	// IsPublic reports whether this is a public import, which causes this file
	// to alias declarations within the imported file. The intended use cases
	// for this feature is the ability to move proto files without breaking
	// existing dependencies.
	//
	// The current file and the imported file must be within proto package.
	IsPublic bool

	// IsWeak reports whether this is a weak import, which does not impose
	// a direct dependency on the target file.
	//
	// Weak imports are a legacy proto1 feature. Equivalent behavior is
	// achieved using proto2 extension fields or proto3 Any messages.
	IsWeak bool
}

FileImport is the declaration for a proto file import.

type FileImports

type FileImports interface {
	// Len reports the number of files imported by this proto file.
	Len() int
	// Get returns the ith FileImport. It panics if out of bounds.
	Get(i int) FileImport
	// contains filtered or unexported methods
}

FileImports is a list of file imports.

type FullName

type FullName string // e.g., "google.protobuf.Field.Kind"

FullName is a qualified name that uniquely identifies a proto declaration. A qualified name is the concatenation of the proto package along with the fully-declared name (i.e., name of parent preceding the name of the child), with a '.' delimiter placed between each Name.

This should not have any leading or trailing dots.

func (FullName) Append

func (n FullName) Append(s Name) FullName

Append returns the qualified name appended with the provided short name.

Invariant: n == n.Parent().Append(n.Name()) // assuming n is valid

func (FullName) IsValid

func (s FullName) IsValid() bool

IsValid reports whether s is a syntactically valid full name. An empty full name is invalid.

func (FullName) Name

func (n FullName) Name() Name

Name returns the short name, which is the last identifier segment. A single segment FullName is the Name itself.

func (FullName) Parent

func (n FullName) Parent() FullName

Parent returns the full name with the trailing identifier removed. A single segment FullName has no parent.

type Kind

type Kind kind

Kind indicates the basic proto kind of a field.

const (
	BoolKind     Kind = 8
	EnumKind     Kind = 14
	Int32Kind    Kind = 5
	Sint32Kind   Kind = 17
	Uint32Kind   Kind = 13
	Int64Kind    Kind = 3
	Sint64Kind   Kind = 18
	Uint64Kind   Kind = 4
	Sfixed32Kind Kind = 15
	Fixed32Kind  Kind = 7
	FloatKind    Kind = 2
	Sfixed64Kind Kind = 16
	Fixed64Kind  Kind = 6
	DoubleKind   Kind = 1
	StringKind   Kind = 9
	BytesKind    Kind = 12
	MessageKind  Kind = 11
	GroupKind    Kind = 10
)

Constants as defined by the google.protobuf.Field.Kind enumeration.

func (Kind) GoString

func (k Kind) GoString() string

GoString returns k as a Go source identifier (e.g., "BoolKind").

func (Kind) IsValid

func (k Kind) IsValid() bool

IsValid reports whether the kind is valid.

func (Kind) String

func (k Kind) String() string

String returns k as a proto source identifier (e.g., "bool").

type List

type List interface {
	// Len reports the number of entries in the List.
	// Get, Set, and Truncate panic with out of bound indexes.
	Len() int

	// Get retrieves the value at the given index.
	// It never returns an invalid value.
	Get(int) Value

	// Set stores a value for the given index.
	// When setting a composite type, it is unspecified whether the set
	// value aliases the source's memory in any way.
	//
	// Set is a mutating operation and unsafe for concurrent use.
	Set(int, Value)

	// Append appends the provided value to the end of the list.
	// When appending a composite type, it is unspecified whether the appended
	// value aliases the source's memory in any way.
	//
	// Append is a mutating operation and unsafe for concurrent use.
	Append(Value)

	// AppendMutable appends a new, empty, mutable message value to the end
	// of the list and returns it.
	// It panics if the list does not contain a message type.
	AppendMutable() Value

	// Truncate truncates the list to a smaller length.
	//
	// Truncate is a mutating operation and unsafe for concurrent use.
	Truncate(int)

	// NewElement returns a new value for a list element.
	// For enums, this returns the first enum value.
	// For other scalars, this returns the zero value.
	// For messages, this returns a new, empty, mutable value.
	NewElement() Value

	// IsValid reports whether the list is valid.
	//
	// An invalid list is an empty, read-only value.
	//
	// Validity is not part of the protobuf data model, and may not
	// be preserved in marshaling or other operations.
	IsValid() bool
}

List is a zero-indexed, ordered list. The element Value type is determined by [FieldDescriptor.Kind]. Providing a Value that is invalid or of an incorrect type panics.

type Map

type Map interface {
	// Len reports the number of elements in the map.
	Len() int

	// Range iterates over every map entry in an undefined order,
	// calling f for each key and value encountered.
	// Range calls f Len times unless f returns false, which stops iteration.
	// While iterating, mutating operations may only be performed
	// on the current map key.
	Range(f func(MapKey, Value) bool)

	// Has reports whether an entry with the given key is in the map.
	Has(MapKey) bool

	// Clear clears the entry associated with they given key.
	// The operation does nothing if there is no entry associated with the key.
	//
	// Clear is a mutating operation and unsafe for concurrent use.
	Clear(MapKey)

	// Get retrieves the value for an entry with the given key.
	// It returns an invalid value for non-existent entries.
	Get(MapKey) Value

	// Set stores the value for an entry with the given key.
	// It panics when given a key or value that is invalid or the wrong type.
	// When setting a composite type, it is unspecified whether the set
	// value aliases the source's memory in any way.
	//
	// Set is a mutating operation and unsafe for concurrent use.
	Set(MapKey, Value)

	// Mutable retrieves a mutable reference to the entry for the given key.
	// If no entry exists for the key, it creates a new, empty, mutable value
	// and stores it as the entry for the key.
	// It panics if the map value is not a message.
	Mutable(MapKey) Value

	// NewValue returns a new value assignable as a map value.
	// For enums, this returns the first enum value.
	// For other scalars, this returns the zero value.
	// For messages, this returns a new, empty, mutable value.
	NewValue() Value

	// IsValid reports whether the map is valid.
	//
	// An invalid map is an empty, read-only value.
	//
	// An invalid message often corresponds to a nil Go map value,
	// but the details are implementation dependent.
	// Validity is not part of the protobuf data model, and may not
	// be preserved in marshaling or other operations.
	IsValid() bool
}

Map is an unordered, associative map. The entry MapKey type is determined by [FieldDescriptor.MapKey].Kind. The entry Value type is determined by [FieldDescriptor.MapValue].Kind. Providing a MapKey or Value that is invalid or of an incorrect type panics.

type MapKey

type MapKey value

MapKey is used to index maps, where the Go type of the MapKey must match the specified key Kind (see [MessageDescriptor.IsMapEntry]). The following shows what Go type is used to represent each proto Kind:

╔═════════╤═════════════════════════════════════╗
║ Go type │ Protobuf kind                       ║
╠═════════╪═════════════════════════════════════╣
║ bool    │ BoolKind                            ║
║ int32   │ Int32Kind, Sint32Kind, Sfixed32Kind ║
║ int64   │ Int64Kind, Sint64Kind, Sfixed64Kind ║
║ uint32  │ Uint32Kind, Fixed32Kind             ║
║ uint64  │ Uint64Kind, Fixed64Kind             ║
║ string  │ StringKind                          ║
╚═════════╧═════════════════════════════════════╝

A MapKey is constructed and accessed through a Value:

k := ValueOf("hash").MapKey() // convert string to MapKey
s := k.String()               // convert MapKey to string

The MapKey is a strict subset of valid types used in Value; converting a Value to a MapKey with an invalid type panics.

func (MapKey) Bool

func (k MapKey) Bool() bool

Bool returns k as a bool and panics if the type is not a bool.

func (MapKey) Int

func (k MapKey) Int() int64

Int returns k as a int64 and panics if the type is not a int32 or int64.

func (MapKey) Interface

func (k MapKey) Interface() interface{}

Interface returns k as an interface{}.

func (MapKey) IsValid

func (k MapKey) IsValid() bool

IsValid reports whether k is populated with a value.

func (MapKey) String

func (k MapKey) String() string

String returns k as a string. Since this method implements fmt.Stringer, this returns the formatted string value for any non-string type.

func (MapKey) Uint

func (k MapKey) Uint() uint64

Uint returns k as a uint64 and panics if the type is not a uint32 or uint64.

func (MapKey) Value

func (k MapKey) Value() Value

Value returns k as a Value.

type Message

type Message interface {
	// Descriptor returns message descriptor, which contains only the protobuf
	// type information for the message.
	Descriptor() MessageDescriptor

	// Type returns the message type, which encapsulates both Go and protobuf
	// type information. If the Go type information is not needed,
	// it is recommended that the message descriptor be used instead.
	Type() MessageType

	// New returns a newly allocated and mutable empty message.
	New() Message

	// Interface unwraps the message reflection interface and
	// returns the underlying ProtoMessage interface.
	Interface() ProtoMessage

	// Range iterates over every populated field in an undefined order,
	// calling f for each field descriptor and value encountered.
	// Range returns immediately if f returns false.
	// While iterating, mutating operations may only be performed
	// on the current field descriptor.
	Range(f func(FieldDescriptor, Value) bool)

	// Has reports whether a field is populated.
	//
	// Some fields have the property of nullability where it is possible to
	// distinguish between the default value of a field and whether the field
	// was explicitly populated with the default value. Singular message fields,
	// member fields of a oneof, and proto2 scalar fields are nullable. Such
	// fields are populated only if explicitly set.
	//
	// In other cases (aside from the nullable cases above),
	// a proto3 scalar field is populated if it contains a non-zero value, and
	// a repeated field is populated if it is non-empty.
	Has(FieldDescriptor) bool

	// Clear clears the field such that a subsequent Has call reports false.
	//
	// Clearing an extension field clears both the extension type and value
	// associated with the given field number.
	//
	// Clear is a mutating operation and unsafe for concurrent use.
	Clear(FieldDescriptor)

	// Get retrieves the value for a field.
	//
	// For unpopulated scalars, it returns the default value, where
	// the default value of a bytes scalar is guaranteed to be a copy.
	// For unpopulated composite types, it returns an empty, read-only view
	// of the value; to obtain a mutable reference, use Mutable.
	Get(FieldDescriptor) Value

	// Set stores the value for a field.
	//
	// For a field belonging to a oneof, it implicitly clears any other field
	// that may be currently set within the same oneof.
	// For extension fields, it implicitly stores the provided ExtensionType.
	// When setting a composite type, it is unspecified whether the stored value
	// aliases the source's memory in any way. If the composite value is an
	// empty, read-only value, then it panics.
	//
	// Set is a mutating operation and unsafe for concurrent use.
	Set(FieldDescriptor, Value)

	// Mutable returns a mutable reference to a composite type.
	//
	// If the field is unpopulated, it may allocate a composite value.
	// For a field belonging to a oneof, it implicitly clears any other field
	// that may be currently set within the same oneof.
	// For extension fields, it implicitly stores the provided ExtensionType
	// if not already stored.
	// It panics if the field does not contain a composite type.
	//
	// Mutable is a mutating operation and unsafe for concurrent use.
	Mutable(FieldDescriptor) Value

	// NewField returns a new value that is assignable to the field
	// for the given descriptor. For scalars, this returns the default value.
	// For lists, maps, and messages, this returns a new, empty, mutable value.
	NewField(FieldDescriptor) Value

	// WhichOneof reports which field within the oneof is populated,
	// returning nil if none are populated.
	// It panics if the oneof descriptor does not belong to this message.
	WhichOneof(OneofDescriptor) FieldDescriptor

	// GetUnknown retrieves the entire list of unknown fields.
	// The caller may only mutate the contents of the RawFields
	// if the mutated bytes are stored back into the message with SetUnknown.
	GetUnknown() RawFields

	// SetUnknown stores an entire list of unknown fields.
	// The raw fields must be syntactically valid according to the wire format.
	// An implementation may panic if this is not the case.
	// Once stored, the caller must not mutate the content of the RawFields.
	// An empty RawFields may be passed to clear the fields.
	//
	// SetUnknown is a mutating operation and unsafe for concurrent use.
	SetUnknown(RawFields)

	// IsValid reports whether the message is valid.
	//
	// An invalid message is an empty, read-only value.
	//
	// An invalid message often corresponds to a nil pointer of the concrete
	// message type, but the details are implementation dependent.
	// Validity is not part of the protobuf data model, and may not
	// be preserved in marshaling or other operations.
	IsValid() bool

	// ProtoMethods returns optional fast-path implementations of various operations.
	// This method may return nil.
	//
	// The returned methods type is identical to
	// google.golang.org/protobuf/runtime/protoiface.Methods.
	// Consult the protoiface package documentation for details.
	ProtoMethods() *methods
}

Message is a reflective interface for a concrete message value, encapsulating both type and value information for the message.

Accessor/mutators for individual fields are keyed by FieldDescriptor. For non-extension fields, the descriptor must exactly match the field known by the parent message. For extension fields, the descriptor must implement ExtensionTypeDescriptor, extend the parent message (i.e., have the same message FullName), and be within the parent's extension range.

Each field Value can be a scalar or a composite type (Message, List, or Map). See Value for the Go types associated with a FieldDescriptor. Providing a Value that is invalid or of an incorrect type panics.

type MessageDescriptor

type MessageDescriptor interface {
	Descriptor

	// IsMapEntry indicates that this is an auto-generated message type to
	// represent the entry type for a map field.
	//
	// Map entry messages have only two fields:
	//	• a "key" field with a field number of 1
	//	• a "value" field with a field number of 2
	// The key and value types are determined by these two fields.
	//
	// If IsMapEntry is true, it implies that FieldDescriptor.IsMap is true
	// for some field with this message type.
	IsMapEntry() bool

	// Fields is a list of nested field declarations.
	Fields() FieldDescriptors
	// Oneofs is a list of nested oneof declarations.
	Oneofs() OneofDescriptors

	// ReservedNames is a list of reserved field names.
	ReservedNames() Names
	// ReservedRanges is a list of reserved ranges of field numbers.
	ReservedRanges() FieldRanges
	// RequiredNumbers is a list of required field numbers.
	// In Proto3, it is always an empty list.
	RequiredNumbers() FieldNumbers
	// ExtensionRanges is the field ranges used for extension fields.
	// In Proto3, it is always an empty ranges.
	ExtensionRanges() FieldRanges
	// ExtensionRangeOptions returns the ith extension range options.
	//
	// To avoid a dependency cycle, this method returns a proto.Message] value,
	// which always contains a google.protobuf.ExtensionRangeOptions message.
	// This method returns a typed nil-pointer if no options are present.
	// The caller must import the descriptorpb package to use this.
	ExtensionRangeOptions(i int) ProtoMessage

	// Enums is a list of nested enum declarations.
	Enums() EnumDescriptors
	// Messages is a list of nested message declarations.
	Messages() MessageDescriptors
	// Extensions is a list of nested extension declarations.
	Extensions() ExtensionDescriptors
	// contains filtered or unexported methods
}

MessageDescriptor describes a message and corresponds with the google.protobuf.DescriptorProto message.

Nested declarations: FieldDescriptor, OneofDescriptor, FieldDescriptor, EnumDescriptor, and/or MessageDescriptor.

type MessageDescriptors

type MessageDescriptors interface {
	// Len reports the number of messages.
	Len() int
	// Get returns the ith MessageDescriptor. It panics if out of bounds.
	Get(i int) MessageDescriptor
	// ByName returns the MessageDescriptor for a message named s.
	// It returns nil if not found.
	ByName(s Name) MessageDescriptor
	// contains filtered or unexported methods
}

MessageDescriptors is a list of message declarations.

type MessageFieldTypes added in v1.26.0

type MessageFieldTypes interface {
	MessageType

	// Enum returns the EnumType for the ith field in MessageDescriptor.Fields.
	// It returns nil if the ith field is not an enum kind.
	// It panics if out of bounds.
	//
	// Invariant: mt.Enum(i).Descriptor() == mt.Descriptor().Fields(i).Enum()
	Enum(i int) EnumType

	// Message returns the MessageType for the ith field in MessageDescriptor.Fields.
	// It returns nil if the ith field is not a message or group kind.
	// It panics if out of bounds.
	//
	// Invariant: mt.Message(i).Descriptor() == mt.Descriptor().Fields(i).Message()
	Message(i int) MessageType
}

MessageFieldTypes extends a MessageType by providing type information regarding enums and messages referenced by the message fields.

type MessageType

type MessageType interface {
	// New returns a newly allocated empty message.
	// It may return nil for synthetic messages representing a map entry.
	New() Message

	// Zero returns an empty, read-only message.
	// It may return nil for synthetic messages representing a map entry.
	Zero() Message

	// Descriptor returns the message descriptor.
	//
	// Invariant: t.Descriptor() == t.New().Descriptor()
	Descriptor() MessageDescriptor
}

MessageType encapsulates a MessageDescriptor with a concrete Go implementation. It is recommended that implementations of this interface also implement the MessageFieldTypes interface.

type MethodDescriptor

type MethodDescriptor interface {
	Descriptor

	// Input is the input message descriptor.
	Input() MessageDescriptor
	// Output is the output message descriptor.
	Output() MessageDescriptor
	// IsStreamingClient reports whether the client streams multiple messages.
	IsStreamingClient() bool
	// IsStreamingServer reports whether the server streams multiple messages.
	IsStreamingServer() bool
	// contains filtered or unexported methods
}

MethodDescriptor describes a method and corresponds with the google.protobuf.MethodDescriptorProto message.

type MethodDescriptors

type MethodDescriptors interface {
	// Len reports the number of methods.
	Len() int
	// Get returns the ith MethodDescriptor. It panics if out of bounds.
	Get(i int) MethodDescriptor
	// ByName returns the MethodDescriptor for a service method named s.
	// It returns nil if not found.
	ByName(s Name) MethodDescriptor
	// contains filtered or unexported methods
}

MethodDescriptors is a list of method declarations.

type Name

type Name string // e.g., "Kind"

Name is the short name for a proto declaration. This is not the name as used in Go source code, which might not be identical to the proto name.

func (Name) IsValid

func (s Name) IsValid() bool

IsValid reports whether s is a syntactically valid name. An empty name is invalid.

type Names

type Names interface {
	// Len reports the number of names in the list.
	Len() int
	// Get returns the ith name. It panics if out of bounds.
	Get(i int) Name
	// Has reports whether s matches any names in the list.
	Has(s Name) bool
	// contains filtered or unexported methods
}

Names represent a list of names.

type OneofDescriptor

type OneofDescriptor interface {
	Descriptor

	// IsSynthetic reports whether this is a synthetic oneof created to support
	// proto3 optional semantics. If true, Fields contains exactly one field
	// with FieldDescriptor.HasOptionalKeyword specified.
	IsSynthetic() bool

	// Fields is a list of fields belonging to this oneof.
	Fields() FieldDescriptors
	// contains filtered or unexported methods
}

OneofDescriptor describes a oneof field set within a given message and corresponds with the google.protobuf.OneofDescriptorProto message.

type OneofDescriptors

type OneofDescriptors interface {
	// Len reports the number of oneof fields.
	Len() int
	// Get returns the ith OneofDescriptor. It panics if out of bounds.
	Get(i int) OneofDescriptor
	// ByName returns the OneofDescriptor for a oneof named s.
	// It returns nil if not found.
	ByName(s Name) OneofDescriptor
	// contains filtered or unexported methods
}

OneofDescriptors is a list of oneof declarations.

type ProtoMessage

type ProtoMessage interface{ ProtoReflect() Message }

ProtoMessage is the top-level interface that all proto messages implement. This is declared in the protoreflect package to avoid a cyclic dependency; use the google.golang.org/protobuf/proto.Message type instead, which aliases this type.

type RawFields

type RawFields []byte

RawFields is the raw bytes for an ordered sequence of fields. Each field contains both the tag (representing field number and wire type), and also the wire data itself.

func (RawFields) IsValid

func (b RawFields) IsValid() bool

IsValid reports whether b is syntactically correct wire format.

type ServiceDescriptor

type ServiceDescriptor interface {
	Descriptor

	// Methods is a list of nested message declarations.
	Methods() MethodDescriptors
	// contains filtered or unexported methods
}

ServiceDescriptor describes a service and corresponds with the google.protobuf.ServiceDescriptorProto message.

Nested declarations: MethodDescriptor.

type ServiceDescriptors

type ServiceDescriptors interface {
	// Len reports the number of services.
	Len() int
	// Get returns the ith ServiceDescriptor. It panics if out of bounds.
	Get(i int) ServiceDescriptor
	// ByName returns the ServiceDescriptor for a service named s.
	// It returns nil if not found.
	ByName(s Name) ServiceDescriptor
	// contains filtered or unexported methods
}

ServiceDescriptors is a list of service declarations.

type SourceLocation

type SourceLocation struct {
	// Path is the path to the declaration from the root file descriptor.
	// The contents of this slice must not be mutated.
	Path SourcePath

	// StartLine and StartColumn are the zero-indexed starting location
	// in the source file for the declaration.
	StartLine, StartColumn int
	// EndLine and EndColumn are the zero-indexed ending location
	// in the source file for the declaration.
	// In the descriptor.proto, the end line may be omitted if it is identical
	// to the start line. Here, it is always populated.
	EndLine, EndColumn int

	// LeadingDetachedComments are the leading detached comments
	// for the declaration. The contents of this slice must not be mutated.
	LeadingDetachedComments []string
	// LeadingComments is the leading attached comment for the declaration.
	LeadingComments string
	// TrailingComments is the trailing attached comment for the declaration.
	TrailingComments string

	// Next is an index into SourceLocations for the next source location that
	// has the same Path. It is zero if there is no next location.
	Next int
}

SourceLocation describes a source location and corresponds with the google.protobuf.SourceCodeInfo.Location message.

type SourceLocations

type SourceLocations interface {
	// Len reports the number of source locations in the proto file.
	Len() int
	// Get returns the ith SourceLocation. It panics if out of bounds.
	Get(int) SourceLocation

	// ByPath returns the SourceLocation for the given path,
	// returning the first location if multiple exist for the same path.
	// If multiple locations exist for the same path,
	// then SourceLocation.Next index can be used to identify the
	// index of the next SourceLocation.
	// If no location exists for this path, it returns the zero value.
	ByPath(path SourcePath) SourceLocation

	// ByDescriptor returns the SourceLocation for the given descriptor,
	// returning the first location if multiple exist for the same path.
	// If no location exists for this descriptor, it returns the zero value.
	ByDescriptor(desc Descriptor) SourceLocation
	// contains filtered or unexported methods
}

SourceLocations is a list of source locations.

type SourcePath

type SourcePath []int32

SourcePath identifies part of a file descriptor for a source location. The SourcePath is a sequence of either field numbers or indexes into a repeated field that form a path starting from the root file descriptor.

See google.protobuf.SourceCodeInfo.Location.path.

func (SourcePath) Equal added in v1.26.0

func (p1 SourcePath) Equal(p2 SourcePath) bool

Equal reports whether p1 equals p2.

func (SourcePath) String added in v1.26.0

func (p SourcePath) String() string

String formats the path in a humanly readable manner. The output is guaranteed to be deterministic, making it suitable for use as a key into a Go map. It is not guaranteed to be stable as the exact output could change in a future version of this module.

Example output:

.message_type[6].nested_type[15].field[3]

type Syntax

type Syntax syntax

Syntax is the language version of the proto file.

const (
	Proto2   Syntax = 2
	Proto3   Syntax = 3
	Editions Syntax = 4
)

func (Syntax) GoString

func (s Syntax) GoString() string

GoString returns s as a Go source identifier (e.g., "Proto2").

func (Syntax) IsValid

func (s Syntax) IsValid() bool

IsValid reports whether the syntax is valid.

func (Syntax) String

func (s Syntax) String() string

String returns s as a proto source identifier (e.g., "proto2").

type Value

type Value value

Value is a union where only one Go type may be set at a time. The Value is used to represent all possible values a field may take. The following shows which Go type is used to represent each proto Kind:

╔════════════╤═════════════════════════════════════╗
║ Go type    │ Protobuf kind                       ║
╠════════════╪═════════════════════════════════════╣
║ bool       │ BoolKind                            ║
║ int32      │ Int32Kind, Sint32Kind, Sfixed32Kind ║
║ int64      │ Int64Kind, Sint64Kind, Sfixed64Kind ║
║ uint32     │ Uint32Kind, Fixed32Kind             ║
║ uint64     │ Uint64Kind, Fixed64Kind             ║
║ float32    │ FloatKind                           ║
║ float64    │ DoubleKind                          ║
║ string     │ StringKind                          ║
║ []byte     │ BytesKind                           ║
║ EnumNumber │ EnumKind                            ║
║ Message    │ MessageKind, GroupKind              ║
╚════════════╧═════════════════════════════════════╝

Multiple protobuf Kinds may be represented by a single Go type if the type can losslessly represent the information for the proto kind. For example, Int64Kind, Sint64Kind, and Sfixed64Kind are all represented by int64, but use different integer encoding methods.

The List or Map types are used if the field cardinality is repeated. A field is a List if [FieldDescriptor.IsList] reports true. A field is a Map if [FieldDescriptor.IsMap] reports true.

Converting to/from a Value and a concrete Go value panics on type mismatch. For example, ValueOf("hello").Int() panics because this attempts to retrieve an int64 from a string.

List, Map, and Message Values are called "composite" values.

A composite Value may alias (reference) memory at some location, such that changes to the Value updates the that location. A composite value acquired with a Mutable method, such as [Message.Mutable], always references the source object.

For example:

// Append a 0 to a "repeated int32" field.
// Since the Value returned by Mutable is guaranteed to alias
// the source message, modifying the Value modifies the message.
message.Mutable(fieldDesc).List().Append(protoreflect.ValueOfInt32(0))

// Assign [0] to a "repeated int32" field by creating a new Value,
// modifying it, and assigning it.
list := message.NewField(fieldDesc).List()
list.Append(protoreflect.ValueOfInt32(0))
message.Set(fieldDesc, list)
// ERROR: Since it is not defined whether Set aliases the source,
// appending to the List here may or may not modify the message.
list.Append(protoreflect.ValueOfInt32(0))

Some operations, such as [Message.Get], may return an "empty, read-only" composite Value. Modifying an empty, read-only value panics.

func ValueOf

func ValueOf(v interface{}) Value

ValueOf returns a Value initialized with the concrete value stored in v. This panics if the type does not match one of the allowed types in the Value union.

func ValueOfBool

func ValueOfBool(v bool) Value

ValueOfBool returns a new boolean value.

func ValueOfBytes

func ValueOfBytes(v []byte) Value

ValueOfBytes returns a new bytes value.

func ValueOfEnum

func ValueOfEnum(v EnumNumber) Value

ValueOfEnum returns a new enum value.

func ValueOfFloat32

func ValueOfFloat32(v float32) Value

ValueOfFloat32 returns a new float32 value.

func ValueOfFloat64

func ValueOfFloat64(v float64) Value

ValueOfFloat64 returns a new float64 value.

func ValueOfInt32

func ValueOfInt32(v int32) Value

ValueOfInt32 returns a new int32 value.

func ValueOfInt64

func ValueOfInt64(v int64) Value

ValueOfInt64 returns a new int64 value.

func ValueOfList

func ValueOfList(v List) Value

ValueOfList returns a new List value.

func ValueOfMap

func ValueOfMap(v Map) Value

ValueOfMap returns a new Map value.

func ValueOfMessage

func ValueOfMessage(v Message) Value

ValueOfMessage returns a new Message value.

func ValueOfString

func ValueOfString(v string) Value

ValueOfString returns a new string value.

func ValueOfUint32

func ValueOfUint32(v uint32) Value

ValueOfUint32 returns a new uint32 value.

func ValueOfUint64

func ValueOfUint64(v uint64) Value

ValueOfUint64 returns a new uint64 value.

func (Value) Bool

func (v Value) Bool() bool

Bool returns v as a bool and panics if the type is not a bool.

func (Value) Bytes

func (v Value) Bytes() []byte

Bytes returns v as a []byte and panics if the type is not a []byte.

func (Value) Enum

func (v Value) Enum() EnumNumber

Enum returns v as a EnumNumber and panics if the type is not a EnumNumber.

func (Value) Equal added in v1.29.0

func (v1 Value) Equal(v2 Value) bool

Equal reports whether v1 and v2 are recursively equal.

  • Values of different types are always unequal.

  • Bytes values are equal if they contain identical bytes. Empty bytes (regardless of nil-ness) are considered equal.

  • Floating point values are equal if they contain the same value. Unlike the == operator, a NaN is equal to another NaN.

  • Enums are equal if they contain the same number. Since Value does not contain an enum descriptor, enum values do not consider the type of the enum.

  • Other scalar values are equal if they contain the same value.

  • Message values are equal if they belong to the same message descriptor, have the same set of populated known and extension field values, and the same set of unknown fields values.

  • List values are equal if they are the same length and each corresponding element is equal.

  • Map values are equal if they have the same set of keys and the corresponding value for each key is equal.

func (Value) Float

func (v Value) Float() float64

Float returns v as a float64 and panics if the type is not a float32 or float64.

func (Value) Int

func (v Value) Int() int64

Int returns v as a int64 and panics if the type is not a int32 or int64.

func (Value) Interface

func (v Value) Interface() interface{}

Interface returns v as an interface{}.

Invariant: v == ValueOf(v).Interface()

func (Value) IsValid

func (v Value) IsValid() bool

IsValid reports whether v is populated with a value.

func (Value) List

func (v Value) List() List

List returns v as a List and panics if the type is not a List.

func (Value) Map

func (v Value) Map() Map

Map returns v as a Map and panics if the type is not a Map.

func (Value) MapKey

func (v Value) MapKey() MapKey

MapKey returns v as a MapKey and panics for invalid MapKey types.

func (Value) Message

func (v Value) Message() Message

Message returns v as a Message and panics if the type is not a Message.

func (Value) String

func (v Value) String() string

String returns v as a string. Since this method implements fmt.Stringer, this returns the formatted string value for any non-string type.

func (Value) Uint

func (v Value) Uint() uint64

Uint returns v as a uint64 and panics if the type is not a uint32 or uint64.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL