Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Go Generics #68

Open
kagxin opened this issue Mar 16, 2022 · 0 comments
Open

Go Generics #68

kagxin opened this issue Mar 16, 2022 · 0 comments
Labels
golang golang相关

Comments

@kagxin
Copy link
Owner

kagxin commented Mar 16, 2022

示例

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 SumIntsOrFloats[K comparable, V Number](m map[K]V) V {
	var s V
	for _, v := range m {
		s += v
	}
	return s
}

// IF 模仿三目运算
func IF[V any](flag bool, a, b V) V {
	if flag {
		return a
	}
	return b
}

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",
		SumIntsOrFloats[string, int64](ints),
		SumIntsOrFloats[string, float64](floats))

	fmt.Printf("Generic Sums, type parameters inferred: %v and %v\n",
		SumIntsOrFloats(ints),
		SumIntsOrFloats(floats))

	fmt.Printf("IF: %+v", IF[int](true, 1, 2))
}

如何理解泛型

有几个关键点:

  • 我们要在 [ ] 中为泛型函数声明它支持的类型(类型约束) func SumIntsOrFloats[K comparable, V Number](m map[K]V) V
  • 我们使用这个函数的时候指定它使用的参数类型,或者让编译器自己推断 IF[int](true, 1, 2), IF(true, 1, 2)
  • 我们可以声明 类型约束
type Number interface {
    int64 | float64
}

新增类型

为了方便泛型使用,新增了两个类型 anycomparable,不过这两种类型都只能用于参数类型约束 不能用于声明变量。

vscode 如何尝试 generics

1、到官网下载安装 go1.18
2、vscode cmd + shift + p
3、选择 Go: Install/Update Tools 勾选更新所有工具

REF

https://go.dev/doc/tutorial/generics
https://go.dev/blog/go1.18

@kagxin kagxin added the golang golang相关 label Mar 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
golang golang相关
Projects
None yet
Development

No branches or pull requests

1 participant