當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO Value.FieldByIndex用法及代碼示例

GO語言"reflect"包中"Value.FieldByIndex"類型的用法及代碼示例。

用法:

func(v Value) FieldByIndex(index []int) Value

FieldByIndex 返回索引對應的嵌套字段。如果評估需要單步執行 nil 指針或不是結構的字段,它會出現Panics。

例子:

package main

import (
	"fmt"
	"reflect"
)

func main() {
	// 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)

}

輸出:

embedded last name: Embedded Doe

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Value.FieldByIndex。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。