使用反射包,您还可以找到结构变量的名称和类型。
package main import ( "fmt" "reflect" ) type Book struct { Id int Title string Price float32 Authors []string } func main() { book := Book{} e := reflect.ValueOf(&book).Elem() for i := 0; i < e.NumField(); i++ { varName := e.Type().Field(i).Name varType := e.Type().Field(i).Type varValue := e.Field(i).Interface() fmt.Printf("%v %v %v\n", varName,varType,varValue) } }
C:\golang\codes>go run example19.go
Id int 0
Title string
Price float32 0
Authors []string []
C:\golang\codes>
Id int 0
Title string
Price float32 0
Authors []string []
C:\golang\codes>