In the Go programming language, is it possible to get the type of a variable as a string?

I am pretty unfamiliar with the Go programming language, and I was trying to find a way to get the type of a variable as a string. So far, I have not found anything that works. I tried using typeof(variableName) to get the type of the variable as a string, but this does not seem valid.

Is there any built-in operator that can get the type of a variable as a string, similar to the JavaScript typeof operator or the Python type operator?

 //Trying to print a variable 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. } 
+6
source share
2 answers

Here's the TypeOf function in the reflect package:

 package main import "fmt" import "reflect" func main() { num := 3 fmt.Println(reflect.TypeOf(num)) } 

It is output:

  int

Update:. You updated your question by indicating that you want the type to be 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 must indicate that you have a choice between calling Name() or String() on Type ; they are sometimes different:

 // Name returns the type name within its package. // It returns an empty string for unnamed types. Name() string 

vs

 // String returns a string representation of the type. // The string representation may use shortened package names // (eg, base64 instead of "encoding/base64") and is not // guaranteed to be unique among types. To test for equality, // compare the Types directly. String() string 
+12
source

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

+14
source

Source: https://habr.com/ru/post/949957/


All Articles