Middle+
What is the reflect package in Go? What is it used for?
sobes.tech AI
Answer from AI
The reflect package in Go provides capabilities for working with types and values at runtime. It allows for dynamically inspecting and modifying objects, obtaining information about types, struct fields, methods, and calling them.
This is useful when data types are unknown in advance or when implementing generic functions, such as serialization, ORM, testing, or libraries that work with different types.
Example of using reflect to get the type name and value of a variable:
package main
import (
"fmt"
"reflect"
)
func main() {
var x float64 = 3.14
v := reflect.ValueOf(x)
t := reflect.TypeOf(x)
fmt.Printf("Type: %s, Value: %v\n", t, v)
}
Here, we obtain the type and value of the variable x at runtime.