In Go (Golang), you can print the keys (fields) and values of a struct by using the fmt package, which provides formatting functions like Printf. To access each field of a struct, you can use reflection provided by the reflect package.
Here's an example of how to print the keys and values of a struct in Go:
go
package main
import (
"fmt"
"reflect"
)
// Define a sample struct
type Person struct {
Name string
Age int
City string
}
func main() {
// Create an instance of the struct
p := Person{Name: "John", Age: 30, City: "New York"}
// Use reflection to get the type and value of the struct
t := reflect.TypeOf(p)
v := reflect.ValueOf(p)
// Iterate over the fields of the struct
for i := 0; i < t.NumField(); i++ {
// Get the field type
field := t.Field(i)
// Get the field value
value := v.Field(i)
// Print the field name (key) and value
fmt.Printf("%s: %v\n", field.Name, value.Interface())
}
}
In this example, we define a Person struct, create an instance of it, and then use the reflect package to iterate over its fields. NumField() gives us the number of fields in the struct, and we use a for loop to go over each field. t.Field(i) gives us the reflect.StructField representing the ith field, from which we can obtain the name with field.Name. v.Field(i) gives us the reflect.Value of the ith field, and value.Interface() is used to get the value in a form that can be passed to fmt.Printf.
When you run the code, you should see the output:
code
Name: John
Age: 30
City: New York
This code will print out all fields of the struct, including unexported (private) fields. If you only want to print exported fields (public), you may add a check using field.PkgPath which is an empty string for exported fields:
go
if field.PkgPath == "" {
fmt.Printf("%s: %v\n", field.Name, value.Interface())
}
Note that using reflection can have a performance impact, so it's not recommended to use it in performance-critical code paths.