package main import ( "fmt" "reflect" ) type Person struct { Name string Age int } func main() { p := Person{Name: "Alice", Age: 25} v := reflect.ValueOf(p) // Get the number of fields in the struct numFields := v.NumField() fmt.Printf("Struct has %d fields\n", numFields) }
package main import ( "fmt" "reflect" ) type Dog struct { Name string Breed string Age int IsAlive bool } func main() { d := Dog{Name: "Buddy", Breed: "Golden Retriever", Age: 5, IsAlive: true} v := reflect.ValueOf(d) // Get the number of fields in the struct numFields := v.NumField() fmt.Printf("Struct has %d fields\n", numFields) }This example is similar to the previous one, but we define a struct `Dog` with four fields. We create an instance of `Dog`, and use reflect to get a `reflect.Value` of the struct. We then call `NumField()` to get the number of fields, which will be 4. Both of these examples use the `reflect` package in Go to get the number of fields in a struct.