Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Go Generics 超入門 / Kyoto.go Remote #28 LT会 (2022/02/23)

luccafort
February 23, 2022

Go Generics 超入門 / Kyoto.go Remote #28 LT会 (2022/02/23)

2022/02/23のKyoto.go Remote #28 LT会 登壇資料です。
https://kyotogo.connpass.com/event/238059/

luccafort

February 23, 2022
Tweet

More Decks by luccafort

Other Decks in Technology

Transcript

  1. 自己紹介 • Kyoto.go オーガナイザー • Kyoto.rb オーガナイザー • Go Conference

    運営メンバー • Money Forward ◦ 技術広報 && ソフトウェアエンジニア ◦ RubyときどきGo • 最近のできごと ◦ 最近親知らずレスになりました ◦ GoCon2022 Springの登壇準備が……
  2. 本日のお品書き • ジェネリクス / Generics • 型パラメータと制約 / Type parameters

    and Constraints • 遊んでみた所感 / Impression ※ 2022/02/23時点でGo 1.18はリリースされていません。
  3. 最低限これだけ抑える概念 • 型パラメータ(type parameters) ◦ 具体的に型が決まってないときに使うものの総称 • 型引数 ◦ ジェネリクスな型や関数に具体的な型を指定する

    ◦ 型推論で省略できる • 制約(constraints) ◦ 型パラメータへの制約として機能する ◦ 事前宣言された制約に any と comparable が追加 • 型セットとかも説明しようと思ったけど多分時間ないのでスキップ
  4. コードで説明 func Min[T int | float64](a, b T) T {

    if a < b { return a } return b } func main() { fmt.Println(Min[int](5, 2)) fmt.Println(Min[float64](3.1, 9.7)) } https://go.dev/play/p/uCZq2OnksPK 型パラメータ 型引数
  5. コードで説明 type ID uint func (id ID) String() string {

    return fmt.Sprintf("%d", id) } func Print[T fmt.Stringer](s []T) { for _, v := range s { fmt.Printf("id: %s,", v.String()) } } func main() { Print([]ID{1, 3, 90, 23}) } https://go.dev/play/p/ZeHIDX1LQyX 制約
  6. まとめ • これまで ◦ それぞれのデータ型ごとの関数を定義 ▪ とても面倒くさい。Goのdisられポイントだった • これから(Go 1.18以降)

    ◦ Genericsを使いデータ型を抽象化することができる ◦ 型パラメータ、型引数、制約あたりを押さえていれば書き始めることができ る。
  7. より詳しくGenerics沼に落ちたいかたはこちら • Tutorial: Getting started with generics ◦ https://go.dev/doc/tutorial/generics •

    go generics for the busy gophers ◦ https://sethops1.net/post/go-generics-for-the-busy-gopher/ • Go 言語にやってくる Generics は我々に何をもたらすのか ◦ https://zenn.dev/mattn/books/4c7de85ec42cb44cf285 • Go 1.18集中連載 ジェネリクス ◦ https://future-architect.github.io/articles/20220209a/
  8. より詳しくGenerics沼に落ちたいかたはこちら • Goにこれから入る機能について ◦ https://docs.google.com/presentation/d/10YX-P5wChDmBRXqUDDWN ThtBXvg81EdS4vhUS_iRtdk/edit#slide=id.p • Go の "Type

    Sets" proposal を読む ◦ https://zenn.dev/nobishii/articles/99a2b55e2d3e50 • What's new in Go 1.18? ◦ https://speakerdeck.com/syumai/whats-new-in-go-1-dot-18