]> Cypherpunks repositories - gostls13.git/commitdiff
reflect: add example for FieldByIndex
authorMostafa Solati <mostafa.solati@gmail.com>
Mon, 8 Jun 2020 17:34:09 +0000 (22:04 +0430)
committerTobias Klauser <tobias.klauser@gmail.com>
Sun, 22 Aug 2021 13:14:19 +0000 (13:14 +0000)
Change-Id: I539453e50ab85ec1b023bc9e329e6451c674e0c9
Reviewed-on: https://go-review.googlesource.com/c/go/+/236937
Reviewed-by: Emmanuel Odeke <emmanuel@orijtech.com>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Emmanuel Odeke <emmanuel@orijtech.com>
TryBot-Result: Go Bot <gobot@golang.org>

src/reflect/example_test.go

index 23c08e4950049ed44f818d1d118ef1892adb1ad9..684bafd64869bb16fb4ad6a5be6dbfdd7c83ebe6 100644 (file)
@@ -166,3 +166,31 @@ func ExampleStructOf() {
        // json:  {"height":0.4,"age":2}
        // value: &{Height:1.5 Age:10}
 }
+
+func ExampleValue_FieldByIndex() {
+       // This example shows a case in which the name of a promoted field
+       // is hidden by another field: FieldByName will not work, so
+       // FieldByIndex must be used instead.
+       type user struct {
+               firstName string
+               lastName  string
+       }
+
+       type data struct {
+               user
+               firstName string
+               lastName  string
+       }
+
+       u := data{
+               user:      user{"Embedded John", "Embedded Doe"},
+               firstName: "John",
+               lastName:  "Doe",
+       }
+
+       s := reflect.ValueOf(u).FieldByIndex([]int{0, 1})
+       fmt.Println("embedded last name:", s)
+
+       // Output:
+       // embedded last name: Embedded Doe
+}