type Person struct { Name string Age int } func main() { p := Person{Name: "John", Age: 30} t := reflect.TypeOf(p) f, ok := t.FieldByName("Name") if ok { fmt.Println(f.Name, f.Type) } }
type Rectangle struct { length float64 breadth float64 } func main() { r := Rectangle{10.0, 5.0} valueOfRect := reflect.ValueOf(r) typeOfRect := valueOfRect.Type() for i := 0; i < valueOfRect.NumField(); i++ { valueField := valueOfRect.Field(i) typeField := typeOfRect.Field(i) fmt.Printf("Name: %s, Value: %v\n", typeField.Name, valueField.Interface()) } }In this example, we have a struct Rectangle with two fields. We create an instance of the struct and obtain a value of its type using the ValueOf function from the reflect package. We then get the type information of the struct and loop through its fields using the NumField and Field functions. We obtain the value and type of each field and print it. The package library used in both the examples is the reflect package from Go standard library.