LoginSignup
0
0

More than 1 year has passed since last update.

goのgenericsチュートリアルを試してみる

Posted at

使用環境

  • Macbook Pro 16inch (Intel)
  • Goland IDE

準備

  1. go 1.18.1をこちらからインストール
  2. Goland IDEのプロジェクトの言語バージョンを1.18に設定(GOROOTとGOPATH両方を設定しました、正しいかはわかりません)
  3. go.modも1.18のものを生成する

Goland IDEを2022バージョンにしないと赤い波線のエラー表示が出ますが、コードは普通に動きます。

実際のコード

こちらはtutorialページから取得したものです。

main.go
package main

import "fmt"

func SumInts(m map[string]int64) int64 {
	var s int64
	for _, v := range m {
		s += v
	}
	return s
}

func SumFloats(m map[string]float64) float64 {
	var s float64
	for _, v := range m {
		s += v
	}
	return s
}

func SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V {
	var s V
	for _, v := range m {
		s += v
	}
	return s
}

func main() {
	ints := map[string]int64{
		"first": 34,
		"second": 12,
	}
	floats := map[string]float64{
		"first": 35.98,
		"second": 12.11,
	}

	fmt.Printf("Non-generic sums %v and %v\n", SumInts(ints), SumFloats(floats))
	fmt.Printf("Generic sums: %v and %v\n", SumIntsOrFloats[string, int64](ints), SumIntsOrFloats[string, float64](floats))
}

go.modも1.18に向くように設定しています。

go.mod
module example/generics

go 1.18

Runした結果

Non-generic sums 46 and 48.089999999999996
Generic sums: 46 and 48.089999999999996
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0