This is a creation in Article, where the information may have evolved or changed.
func (ORM *model ) SCANPK (Output interface{}) *model {if reflect. TypeOf (reflect. Indirect (reflect. ValueOf (output)). Interface ()). Kind () = = reflect. Slice {slicevalue: = reflect. Indirect (reflect. ValueOf (Output)) Sliceelementtype: = Slicevalue.type (). Elem () for I: = 0; I < Sliceelementtype.numfield (); i++ {bb: = Sliceelementtype.field (i). Tag if BB. Get ("beedb") = = "PK" | | Reflect. ValueOf (BB). String () = = "PK" {orm. PrimaryKey = Sliceelementtype.field (i). Name}}} else {tt: = reflect. TypeOf (reflect. Indirect (reflect. ValueOf (output)). Interface ()) for I: = 0; I < TT. Numfield (); i++ {bb: = TT. Field (i). Tag if BB. Get ("beedb") = = "PK" | | Reflect. ValueOf (BB). String () = = "PK" {orm. PrimaryKey = TT. Field (i). Name}}} return orm}
began to see Xie da beedb, the result is Model.ScanPk(interface{})
stuck, mainly on the function of some reflection-related APIs do not understand, then from the reflection began to study it.
First of all, the introduction of ScanPK
several data structures involved, this will only write to the function related to the data structure related fields, if interested in further research, please move Golang reflect
- Type represents the data structure of the structure type, and some of the fields are declared as follows:
Type type interface {// type of this type Kind () Kind //Find the first field of the Type field (i int) Structfield //Number of fields Numfield () int}
Value represents the data structure of the structure value, and some of the fields are declared as follows:
The enumeration values for the Kind go language built-in type are declared as follows:
Const ( Invalid Kind = Iota Bool Int Int8 Int16 Int32 Int64 Uint Uint8 Uint16 Uint32 Uint64 Uintptr Float32 Float64 Complex64 Complex128 Array Chan Func Interface Map Ptr Slice String Struct Unsafepointer)
- Structfield is used to describe a field of a data structure, and some fields are declared as follows:
Type Structfield struct { //The name of this field name string Tag Structtag//Comment of this field}
- Structtag Structfield has a tag field, which is a supplement to the properties of the owning field. For example, there is now a custom data structure declared as follows:
Type person struct { name string ' JSON: ' Name ' ' Age int}
Unlike the C language, where the name field is declared, a string surrounded by an inverted quotation mark (') is added, and the rule of the string is 键名:"值"
. When this type of structure is reflected, the enclosing string is parsed into StructTag
, and a function can be used StructTag.Get(key string)
to obtain a value.
Here, the data structures that need to be used are all accounted for, the most important of which are two data structures Value、Type
, one represents the value, and the other represents the type. Let's look at a few more functions next.