Golang reflect.StructField() example
package reflect
Golang reflect.StructField() usage example
package main
import (
"fmt"
"reflect"
)
type A struct {
A fmt.ScanState "Tag A" // index 0
AB B "Tag A of type B struct" // index 1
B "Tag B" // index 2 -embedded field
}
type B struct {
B0 string
B1 int
}
func main() {
var a A
var typeof reflect.Type = reflect.TypeOf(a)
var field reflect.StructField = typeof.Field(0) // index 0
fmt.Println("Name : ", field.Name)
fmt.Println("PkgPath : ", field.PkgPath) //<--- only applicable if the field name is small cap(unexported)
fmt.Println("Type : ", field.Type)
fmt.Println("Tag : ", field.Tag)
fmt.Println("Offset : ", field.Offset)
fmt.Println("Index : ", field.Index)
fmt.Println("Anonymous : ", field.Anonymous)
fmt.Println("// --------------------------------------------------")
field = typeof.Field(1) // index 1
fmt.Println("Name : ", field.Name)
fmt.Println("PkgPath : ", field.PkgPath) //<--- only applicable if the field name is small cap(unexported)
fmt.Println("Type : ", field.Type)
fmt.Println("Tag : ", field.Tag)
fmt.Println("Offset : ", field.Offset)
fmt.Println("Index : ", field.Index)
fmt.Println("Anonymous : ", field.Anonymous)
fmt.Println("// --------------------------------------------------")
field = typeof.Field(2) // index 2
fmt.Println("Name : ", field.Name)
fmt.Println("PkgPath : ", field.PkgPath) //<--- only applicable if the field name is small cap(unexported)
fmt.Println("Type : ", field.Type)
fmt.Println("Tag : ", field.Tag)
fmt.Println("Offset : ", field.Offset)
fmt.Println("Index : ", field.Index)
fmt.Println("Anonymous : ", field.Anonymous) // TRUE because it is embedded field
}
Play at : http://play.golang.org/p/JjzPzPe8UP
Reference :
Advertisement
Something interesting
Tutorials
+10.2k Golang : Use regular expression to get all upper case or lower case characters example
+5.8k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+14.4k Golang : Find network of an IP address
+7.6k Android Studio : AlertDialog to get user attention example
+22.2k Golang : Convert seconds to minutes and remainder seconds
+5.3k Golang : Pad file extension automagically
+22.1k Golang : Match strings by wildcard patterns with filepath.Match() function
+13.4k Golang : Increment string example
+12.1k Golang : md5 hash of a string
+51.1k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+43.5k Golang : Get hardware information such as disk, memory and CPU usage
+24.5k Golang : Change file read or write permission example