下面的代码片段声明了具有字段A、B和C的结构类型Test。我们需要验证字段Z是否存在于结构类型Test中。

示例代码:

package main

import (
	"log"
	"reflect"
)

func main() {
	type test struct {
		A bool
		B bool
		C bool
	}

	v := new(test)
	metaValue := reflect.ValueOf(v).Elem()

	for _, name := range []string{"A", "C", "Z"} {
		field := metaValue.FieldByName(name)
		if field == (reflect.Value{}) {
			log.Printf("Field %s not exist in struct", name)
		}
	}
}

输出:

2009/11/10 23:00:00 Field Z not exist in struct