Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In the Go programming language, is it possible to obtain a variable's type as a string?

Tags:

go

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.
}
like image 304
Anderson Green Avatar asked Jul 22 '13 02:07

Anderson Green


2 Answers

If you just want to print the type then: fmt.Printf("%T", num) will work. http://play.golang.org/p/vRC2aahE2m

like image 75
Jeremy Wall Avatar answered Oct 08 '22 13:10

Jeremy Wall


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
like image 23
Darshan Rivka Whittle Avatar answered Oct 08 '22 14:10

Darshan Rivka Whittle