From: Mostafa Solati Date: Mon, 8 Jun 2020 17:34:09 +0000 (+0430) Subject: reflect: add example for FieldByIndex X-Git-Tag: go1.18beta1~1681 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=bd6845965c;p=gostls13.git reflect: add example for FieldByIndex Change-Id: I539453e50ab85ec1b023bc9e329e6451c674e0c9 Reviewed-on: https://go-review.googlesource.com/c/go/+/236937 Reviewed-by: Emmanuel Odeke Reviewed-by: Ian Lance Taylor Run-TryBot: Emmanuel Odeke TryBot-Result: Go Bot --- diff --git a/src/reflect/example_test.go b/src/reflect/example_test.go index 23c08e4950..684bafd648 100644 --- a/src/reflect/example_test.go +++ b/src/reflect/example_test.go @@ -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 +}