Reputation: 31800
I'm fairly unfamiliar with the Go programming language, and I've been trying to find a way to get the type of a variable as a string. So far, I haven't found anything that works. I've tried using typeof(variableName)
to obtain a variable's type as a string, but this doesn't appear to be valid.
Does Go have any built-in operator that can obtain a variable's type as a string, similar to JavaScript's typeof
operator or Python's type
operator?
//Trying to print a variable's type as a string:
package main
import "fmt"
func main() {
num := 3
fmt.Println(typeof(num))
//I expected this to print "int", but typeof appears to be an invalid function name.
}
Upvotes: 7
Views: 2518
Reputation: 25237
If you just want to print the type then: fmt.Printf("%T", num)
will work. http://play.golang.org/p/vRC2aahE2m
Upvotes: 14
Reputation: 34031
There's the TypeOf
function in the reflect
package:
package main
import "fmt"
import "reflect"
func main() {
num := 3
fmt.Println(reflect.TypeOf(num))
}
This outputs:
int
Update: You updated your question specifying that you want the type as a string. TypeOf
returns a Type
, which has a Name
method that returns the type as a string. So
typeStr := reflect.TypeOf(num).Name()
Update 2: To be more thorough, I should point out that you have a choice between calling Name()
or String()
on your Type
; they're sometimes different:
// Name returns the type's name within its package.
// It returns an empty string for unnamed types.
Name() string
versus:
// String returns a string representation of the type.
// The string representation may use shortened package names
// (e.g., base64 instead of "encoding/base64") and is not
// guaranteed to be unique among types. To test for equality,
// compare the Types directly.
String() string
Upvotes: 13