Is reflected in the program can be run and check the value of variables, their types are determined.
reflect package implements runtime reflection.
Creating a query string to receive any value of any data type:
func createQuery(q interface{}) string { }
reflect.Type interface {} represents the particular type, and it represents a specific value reflect.Value. reflect.TypeOf () and reflect.ValueOf () function returns two reflect.Type and reflect.Value respectively.
Type
It represents interface{}
the actual type of (in this case main.Order
), and Kind
represents a particular category of this type (in this case struct
).
NumField()
The method returns the number of fields in the structure, and the Field(i int)
method returns the field i
of reflect.Value
.
func createQuery(q interface{}) { if reflect.ValueOf(q).Kind() == reflect.Struct { v := reflect.ValueOf(q) fmt.Println("Number of fields", v.NumField()) for i := 0; i < v.NumField(); i++ { fmt.Printf("Field:%d type:%T value:%v\n", i, v.Field(i), v.Field(i)) } } }
Int and String can be taken as the value reflect.Value int64 and string respectively.
package main import ( "fmt" "reflect" ) type order struct { ordId int customerId int } type employee struct{ name string id int address string salary int country string } func createQuery(q interface{}){ if reflect.ValueOf(q).Kind() == reflect.Struct { t := reflect.TypeOf(q).Name() query := fmt.Sprintf("insert into %s values(", t) v := reflect.ValueOf(q) for i:=0; i < v.NumField(); i++{ switch v.Field(i).Kind(){ case reflect.Int: if i == 0{ query = fmt.Sprintf("%s%d", query, v.Field(i).Int()) } else { query = fmt.Sprintf("%s, %d", query, v.Field(i).Int()) } case reflect.String: if i==0 { query = fmt.Sprintf("%s\"%s\"", query, v.Field(i).String()) } else { query = fmt.Sprintf("%s, \"%s\"", query, v.Field(i).String()) } default: fmt.Println("Unsupported type") return } } query = fmt.Sprintf("%s)", query) fmt.Println(query) return } fmt.Println("Unsupported type") } func main(){ o := order{ ordId: 44, customerId: 100, } createQuery(o) e := employee{ name: "Wang", address: "HN", country: "CN", id: 10000, salary: 10000, } createQuery(e) i := 100 createQuery(i) } output: insert into order values(44, 100) insert into employee values("Wang", 10000, "HN", 10000, "CN") Unsupported type
reference: