package main import ( "fmt" "reflect" ) type Person struct { Name string Age int Address string } func main() { p := Person{"John Doe", 25, "123 Main Street"} fmt.Println("Number of fields in Person struct:", reflect.TypeOf(p).NumField()) }
Number of fields in Person struct: 3
package main import ( "fmt" "reflect" ) type Person struct { Name string Age int Address string } func main() { p := Person{"John Doe", 25, "123 Main Street"} t := reflect.TypeOf(p) for i := 0; i < t.NumField(); i++ { field := t.Field(i) fmt.Printf("Field %d: %s (%s)\n", i, field.Name, field.Type) } }
Field 0: Name (string) Field 1: Age (int) Field 2: Address (string)Package Library: The NumField method is part of the reflect package in Go.