Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

golang 1.18 正式版本,支持泛型


func TestGeneric(t *testing.T) {
	x := map[string]int{"tom": 12, "jelly": 7}
	res := Sums[string, int](x)
	log.Println(res)

    stuC := StuCross[string]{
		score: "成绩",
	}
	log.Println(stuC)
}

//指定函数参数类型约束
func Sums[K string, V int | float32](m map[K]V) V {
	var x V
	for _, v := range m {
		x += v
	}
	return x
}

type StuCross[K string] struct {
	score K
}