古老的榕树

Go 1.18 即将发布

潘军杰 发表于 2022-02-19 15:02 阅读(794) 评论(1) 赞(3)

看 Go 官网博客介绍,Go 1.18 Bata2 已经发布,正式版将会在 2022年3月份发布出来,这个版本绝对是一个里程碑的版本,不亚于 1.0 的发布。这次主要是语言加入了泛型,影响是很深远的,基本之前的底层包的类型和函数都被翻了一遍,并且以后使用带泛型的 Go 语言,在使用上也是有很大的区别的,2022年,注定很多第三方类库会因此做出相应的改动,到时将是非常热闹非常造的一年。

使用 Go 有很多年了,从 Java C# 转过来,发现没有泛型,多态性,Go 语言写出来的东西,会多出不少的代码,传统面向对象的语言有不少可取之处,希望 Go 除了能做一些创新性的东西,也可以接纳其他语言的大优点。

没有泛型的使用示例:

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("Non-Generic Sums: %v and %v\n",
        SumInts(ints),
        SumFloats(floats))
}


有泛型的使用示例:

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

fmt.Printf("Generic Sums: %v and %v\n",
    SumIntsOrFloats[string, int64](ints),
    SumIntsOrFloats[string, float64](floats))

官方博客给了一个完整的代码:

package main

import "fmt"

type Number interface {
    int64 | float64
}

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("Non-Generic Sums: %v and %v\n",
        SumInts(ints),
        SumFloats(floats))

    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("Generic Sums with Constraint: %v and %v\n",
        SumNumbers(ints),
        SumNumbers(floats))
}

// SumInts adds together the values of m.
func SumInts(m map[string]int64) int64 {
    var s int64
    for _, v := range m {
        s += v
    }
    return s
}

// SumFloats adds together the values of m.
func SumFloats(m map[string]float64) float64 {
    var s float64
    for _, v := range m {
        s += v
    }
    return s
}

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

// SumNumbers sums the values of map m. Its supports both integers
// and floats as map values.
func SumNumbers[K comparable, V Number](m map[K]V) V {
    var s V
    for _, v := range m {
        s += v
    }
    return s
}
标签: Go 泛型
1 条网友评论

1 楼: Go 使者 发表于 2022-03-16 09:42:57   回复 TA

Go 1.8 已经在 2022年3月16日正式发布,欢迎使用!
称呼*
邮箱*
内容*
验证码*
验证码 看不清换张