In the Go programming language, is it possible to obtain a variable's type as a string? -
i'm unfamiliar go programming language, , i've been trying find way type of variable string. far, haven't found works. i've tried using typeof(variablename)
obtain variable's type string, doesn't appear valid.
does go have built-in operator can obtain variable's type string, similar javascript's typeof
operator or python's type
operator?
//trying print variable's type string: package main import "fmt" func main() { num := 3 fmt.println(typeof(num)) //i expected print "int", typeof appears invalid function name. }
there's typeof
function in reflect
package:
package main import "fmt" import "reflect" func main() { num := 3 fmt.println(reflect.typeof(num)) }
this outputs:
int
update: updated question specifying want type string. typeof
returns type
, has name
method returns type string. so
typestr := reflect.typeof(num).name()
update 2: more thorough, should point out have choice between calling name()
or string()
on type
; they're different:
// name returns type's name within package. // returns empty string unnamed types. name() string
versus:
// string returns string representation of type. // string representation may use shortened package names // (e.g., base64 instead of "encoding/base64") , not // guaranteed unique among types. test equality, // compare types directly. string() string
Comments
Post a Comment