【Go官方文档】Getting started with generics

引用

环境配置:

  • 系统:Windows11
  • 编辑器:vscode

🌶️ 创建项目

  1. 创建项目文件夹generics并用vscode打开
  2. 在终端执行命令:
1
go mod init example/generics
  1. 创建文件main.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main

import "fmt"

// 定义约束
type Number interface {
	int64 | float64
}

// SumIntsOrFloats sums the values of map m. It supports both int64 and float64
// as types for map values.
func SumNumbers[K comparable, V Number](m map[K]V) V {
	var s V
	for _, v := range m {
		s += v
	}
	return s
}

func main() {
	// Initialize a map for the integer values
	ints := map[string]int64{
		"first":  34,
		"second": 12,
	}

	// Initialize a map for the float values
	floats := map[string]float64{
		"first":  35.98,
		"second": 26.99,
	}

	fmt.Printf("Generic Sums: %v and %v\n",
		SumNumbers(ints),
		SumNumbers(floats))
}

🥕 运行代码

  1. 在终端执行命令:
1
go run .
  1. 执行结果:
1
Generic Sums: 46 and 62.97
0%