Skip to content

Commit 05be61f

Browse files
committed
reflect/protoreflect: add more docs on Value aliasing
Fixes golang/protobuf#1346 Change-Id: I9deb36e1c5e4f28c1c7e99ca64260c7a86af4ea1 Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/339569 Trust: Damien Neil <[email protected]> Trust: Joe Tsai <[email protected]> Run-TryBot: Damien Neil <[email protected]> Reviewed-by: Joe Tsai <[email protected]>
1 parent b03064a commit 05be61f

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

reflect/protoreflect/value_union.go

+25
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,31 @@ import (
4141
// Converting to/from a Value and a concrete Go value panics on type mismatch.
4242
// For example, ValueOf("hello").Int() panics because this attempts to
4343
// retrieve an int64 from a string.
44+
//
45+
// List, Map, and Message Values are called "composite" values.
46+
//
47+
// A composite Value may alias (reference) memory at some location,
48+
// such that changes to the Value updates the that location.
49+
// A composite value acquired with a Mutable method, such as Message.Mutable,
50+
// always references the source object.
51+
//
52+
// For example:
53+
// // Append a 0 to a "repeated int32" field.
54+
// // Since the Value returned by Mutable is guaranteed to alias
55+
// // the source message, modifying the Value modifies the message.
56+
// message.Mutable(fieldDesc).(List).Append(protoreflect.ValueOfInt32(0))
57+
//
58+
// // Assign [0] to a "repeated int32" field by creating a new Value,
59+
// // modifying it, and assigning it.
60+
// list := message.NewField(fieldDesc).(List)
61+
// list.Append(protoreflect.ValueOfInt32(0))
62+
// message.Set(fieldDesc, list)
63+
// // ERROR: Since it is not defined whether Set aliases the source,
64+
// // appending to the List here may or may not modify the message.
65+
// list.Append(protoreflect.ValueOfInt32(0))
66+
//
67+
// Some operations, such as Message.Get, may return an "empty, read-only"
68+
// composite Value. Modifying an empty, read-only value panics.
4469
type Value value
4570

4671
// The protoreflect API uses a custom Value union type instead of interface{}

0 commit comments

Comments
 (0)