8.2 ジェネリクスの導入
Goの開発チームはジェネリクスの既知の実装方法の問題を10年間研究して、実現可能な方法を考えだし「Type Parameters Proposal」にまとめた
ジェネリック型を使用することで、コンパイル時の型安全性のチェックを行うことができる
code:go
package main
import (
"fmt"
)
type StackT comparable struct { // comparableは組み込みの比較可能な型のインタフェース vals []T
}
func (s *StackT) Push(val T) { s.vals = append(s.vals, val)
}
func (s *StackT) Pop() (T, bool) { if len(s.vals) == 0 {
var zero T
return zero, false
}
return top, true
}
func (s StackT) Contains(val T) bool { for _, v := range s.vals {
if v == val {
return true
}
}
return false
}
func main() {
var s Stackint // Stackの要素の型(int)を指定する s.Push(10)
s.Push(20)
s.Push(30)
fmt.Println(s.Contains(10)) // true
fmt.Println(s.Contains(5)) // false
s.Push("hoge") // ./prog.go:41:9: cannot use "hoge" (untyped string constant) as int value in argument to s.Push
}