2013-07-22 4 views
6

私はGoプログラミング言語にはあまり慣れていませんし、変数の型を文字列として取得する方法を見つけようとしています。これまでのところ、私は動作するものは見つかりませんでした。私はtypeof(variableName)を使って変数の型を文字列として取得しようとしましたが、これは有効ではないようです。Goプログラミング言語では、変数の型を文字列として取得できますか?

Goには、JavaScriptのtypeof演算子やPythonのtype演算子と同様に、変数の型を文字列として取得できるビルトイン演算子がありますか?

//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. 
} 

答えて

12

TypeOf機能はreflectパッケージにあります:

package main 

import "fmt" 
import "reflect" 

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

この出力は:

 
int 

更新:あなたは文字列としてタイプをしたいことを指定するあなたの質問を更新しました。 TypeOfは、Nameメソッドを持つTypeを返します。このメソッドは、型を文字列として返します。だから、

typeStr := reflect.TypeOf(num).Name() 

アップデート2:より徹底されるように、私はあなたのTypeName()またはString()を呼び出すかの選択を持っていることを指摘すべきです。彼らは時々異なっている:対

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

// 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 
関連する問題