goで空インターフェースを宣言するには?
Go言語では、空のインターフェイスを宣言するために、interface{}を使うことができます。下のコードはその例です:
package main
import "fmt"
func main() {
var emptyInterface interface{}
emptyInterface = 5
fmt.Println(emptyInterface)
emptyInterface = "Hello"
fmt.Println(emptyInterface)
emptyInterface = true
fmt.Println(emptyInterface)
}
インターフェイスvar emptyInterface interface{} を用いて、空インターフェイスemptyInterfaceを上記コードのように宣言します。空インターフェイスはどんな型でも受け取ることができます。サンプルでは、空インターフェイスにそれぞれ整数、文字列、真偽値を代入し、fmt.Printlnを使って出力しています。出力結果は次のようになります:
5
Hello
true