整理したものはTech sheetsにあるよ

2016年10月18日火曜日

[Golang]Goの型付き比較をみてみよう

みんなー!モケラだよ

今日は、Go言語の型のおはなしだよ。

Goは、こんな風に知ってる型の別名を作れるよね!


type Moke int

このMokeという型はintの別名で、キャストするには次のように書くんだったね!

val :=  Moke(1)
val2 := int(val)

じゃあ、意味としては同じ1を次のようなmapにいれると、どうなるかな?

type Moke int
type Piyo int

func main() {
        hash := map[interface{}]string{
                Moke(1): "Moke",
                Piyo(1): "Piyo",
        }
        fmt.Printf("1 = %s\n", hash[1])
        fmt.Printf("Moke(1) = %s\n", hash[Moke(1)])
        fmt.Printf("Piyo(1) = %s\n", hash[Piyo(1)])
}

1が3個mapに入ってるね。実行結果はこちら!
$ go run main.go
1 =
Moke(1) = Moke
Piyo(1) = Piyo

比較は、型も考慮してやってくれるのが、Go言語!