Reflection in Go
Go has support for reflection, which allows you to inspect and manipulate values at runtime.
The reflect package provides functions and types for working with reflection in Go.
Here's an example of using reflection to inspect the type of a variable:
func main() {
x := 42
t := reflect.TypeOf(x)
fmt.Println(t.Name()) // prints "int"
}
In this example, we create a new variable called x and inspect its type by using the reflect.TypeOf() function. We then print the name of the type by using the t.Name() method.
Reflection is a powerful feature of Go, but it should be used sparingly, as it can be slow and make code harder to understand and maintain.
No comments:
Post a Comment