In Go, package-level variables are not directly accessible or manipulable using reflection because they are not exported. However, you can still inspect and manipulate them with some workarounds. Here's how you can do it:
package mypackage
var myVariable int
// Exported function to access the package-level variable
func GetMyVariable() int {
return myVariable
}
package main
import (
"fmt"
"reflect"
"mypackage"
)
func main() {
funcValue := reflect.ValueOf(mypackage.GetMyVariable)
result := funcValue.Call(nil)
fmt.Println(result[0].Int()) // prints the value of myVariable
}
By following these steps, you can indirectly inspect and manipulate package-level variables using reflection in Go.