reflect: add example for FieldByIndex

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>
This commit is contained in:
Mostafa Solati 2020-06-08 22:04:09 +04:30 committed by Tobias Klauser
parent 96d816c574
commit bd6845965c

View 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
}