Find Out Golang Variable Type

Kevin FOO
Jan 12, 2021

--

How to find out the variable type of the variable you are using in Go/Golang? I had this issue when I was using Bolt DB package and tried to share the connection by passing the db variable around.

To return it, your function needs to declare the variable type it is returning. To pass it into a function, the function needs to declare the variable type being passed in. To find out the variable type, I used the reflect package.

package mainimport (
"fmt"
"reflect"
)
func main() {
s := "golang"
i := 1
f := 3.142

fmt.Println(reflect.TypeOf(s))
fmt.Println(reflect.TypeOf(i))
fmt.Println(reflect.TypeOf(f))
}

The output of the codes above will be

string
int
float64

< Back to all the stories I had written

--

--

Kevin FOO
Kevin FOO

Written by Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.

No responses yet