作者回复: 非常感谢指出这个问题。你学得非常细致,正确的代码如下,github上的代码也会修正。
if reflect.TypeOf(st).Kind() != reflect.Ptr {
return errors.New("the first param should be a pointer to the struct type.")
}
// Elem() 获取指针指向的值
if reflect.TypeOf(st).Elem().Kind() != reflect.Struct {
return errors.New("the first param should be a pointer to the struct type.")
}
作者回复: 可以啊。你还可以利用我们接先来课程中涉及的性能分析方法来分析一下影响。
作者回复: Elem()返回的是值Value,而Type()之后返回的是类型。
你运行以下两行代码就会清楚了:
fmt.Println("--", (reflect.ValueOf(st)).Elem())
fmt.Println("**", (reflect.ValueOf(st)).Elem().Type())
作者回复: 以下是FieldByName的定义,可见返回值是StructField类型。
// FieldByName returns the struct field with the given name
// and a boolean indicating if the field was found.
FieldByName(name string) (StructField, bool)
// A StructField describes a single field in a struct.
type StructField struct {
// Name is the field name.
Name string
// PkgPath is the package path that qualifies a lower case (unexported)
// field name. It is empty for upper case (exported) field names.
// See https://golang.org/ref/spec#Uniqueness_of_identifiers
PkgPath string
Type Type // field type
Tag StructTag // field tag string
Offset uintptr // offset within struct, in bytes
Index []int // index sequence for Type.FieldByIndex
Anonymous bool // is an embedded field
}
作者回复: 因为传入的结构的实例里面包含两个field (Name和Age)所以重复了两遍,
第一个输出是由于 Name和Age都还没有被赋值(Name位空字符串,Age为0,都是缺省值)
第二个输出是由于Name已经被赋值了“Mike”