kagxin / blog

个人博客:技术、随笔、生活
https://github.com/kagxin/blog/issues
7 stars 0 forks source link

Go Generics #68

Open kagxin opened 2 years ago

kagxin commented 2 years ago

示例

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))
}

如何理解泛型

有几个关键点:

新增类型

为了方便泛型使用,新增了两个类型 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