TOC

Go 泛型的最新动态

Go 1.8 已经功能冻结,最后关头,类型约束(类型列表)的语法发生调整。

type Addable interface { 
    type int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr, float32, float64
}

改成:

type Addable interface {
    int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | uintptr | float32 | float64
}

可以到 gotipplay 上尝尝鲜:https://gotipplay.golang.org/p/h52WOBn0IVS

package main

import (
    "fmt"
)

type Addable interface {
    int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | uintptr | float32 | float64
}

func Add[T Addable](a, b T) T {
    return a + b
}

func main() {
    a, b := 1, 2
    fmt.Println(Add(a, b))
    c, d := 1.0, 2.0
    fmt.Println(Add(c, d))
    fmt.Println("Hello, playground")
}