Go Generics Concise Tutorial

Please use generics after 1.18

The code of this article comes from Tutorial: Getting started with generics. It is still relatively simple. This article (written by myself) will be continuously updated.

see the first example

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

// 累加float
func SumFloats(m map[string]float64) float64 {
    var s float64
    for _, v := range m {
        s += v
    }
    return s
}
复制代码

It's like this when called:

func main() {
    // 初始化int map 
    ints := map[string]int64{
        "first":  34,
        "second": 12,
    }

    // 初始化float map
    floats := map[string]float64{
        "first":  35.98,
        "second": 26.99,
    }

    fmt.Printf("Non-Generic Sums: %v and %v\n",
        SumInts(ints),
        SumFloats(floats))
}
复制代码

These two functions are obviously two-in-one. So, go added a type declaration in 1.18

func[在这里写啦!]()
复制代码

As above, it can be completed as:

func SumIntsOrFloats[K comparable, V int64 | float64](m map[K]V) V
复制代码

Comparable is an adaptive type. Adding | can indicate that it can be two types. How about it? Does it taste like ts?

A more specific implementation is as follows:

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

Another puzzling thing is when to use comparable.

It allows any type whose values ​​may be used as an operand of the comparison operators ==and !=. Go requires that map keys be comparable. It allows values ​​expressed with == and !=. Go requires map keys to be comparable

If you need to use it in multiple places, you can use

type Number interface {
    int64 | float64
}
复制代码

Save writing union types everywhere.

func SumNumbers[K comparable, V Number](m map[K]V) V {
    var s V
    for _, v := range m {
        s += v
    }
    return s
}
复制代码

but! It is not possible to use Type in other places, it can only be used in [].

  1. m:= map[string]Numberis not possible
  2. func ReturnSomthing() Number { return 1}still doesn't work

any can replace interface{}, like this:

m:= map[string]any{
        "1": 2,
        "2":"GKD!",
    }
复制代码

1.18 comes out with generics, what impact will it have on go in the future? At present, 2022-04-17 has not seen drastic changes, but at present, only one can be predicted: go's interview questions will be written in small volumes. I think go is very good. :) Welcome other brothers to give it a try, it's free anyway.

Guess you like

Origin juejin.im/post/7087528794873380894