涛子 - 简单就是美

成单纯魁增,永继振国兴,克复宗清政,广开家必升

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

http://events.jianshu.io/p/3ff594bb87de
https://www.zhihu.com/question/318138275/answer/2127814257

Go语言的泛型(Generic)叫做类型参数。泛型可以让我们代码适应不同类型的参数

/* 
   声明一个带有泛型的函数
   T 指类型参数,就是一个参数,代表类型
   Constraint 是对类型参数T的约束,限制T的取值, 可以是int、string、any等类型,any可以是任意类型的意思
   s 是要打印的参数
*/

func name[T {Constraint}](s T) {}

函数名和函数参数列表之间插入了一组方括号,来表示类型参数。
跟函数参数一样,我们需要为每一个类型参数指定「类型」,这种类型的类型Go语言称之为约束。

1. Constrained Generic Type

package main

import (
	"fmt"
)

type Stringer = interface {
    String() string
}

type Integer int

func (i Integer) String() string {
    return fmt.Sprintf("%d", i)
}

type String string

func (s String) String() string {
    return string(s)
}

type Student struct {
    Name string
    ID   int
    Age  float64
}

func (s Student) String() string {
    return fmt.Sprintf("%s %d %0.2f", s.Name, s.ID, s.Age)
}

func addStudent[T Stringer](students []T, student T) []T {
    return append(students, student)
}

func main() {
    students := []String{}
    result := addStudent[String](students, "Michael")
    result = addStudent[String](result, "Jennifer")
    result = addStudent[String](result, "Elaine")
    fmt.Println(result)

    students1 := []Integer{}
    result1 := addStudent[Integer](students1, 45)
    result1 = addStudent[Integer](result1, 64)
    result1 = addStudent[Integer](result1, 78)
    fmt.Println(result1)

    students2 := []Student{}
    result2 := addStudent[Student](students2, Student{"John", 213, 17.5})
    result2 = addStudent[Student](result2, Student{"James", 111, 18.75})
    result2 = addStudent[Student](result2, Student{"Marsha", 110, 16.25})
    fmt.Println(result2)
}

2. Constrained Generic Type

package main

import (
    "fmt"
)

type Student struct {
    Name string
    ID   int
    Age  float64
}

func addStudent[T any](students []T, student T) []T {
    return append(students, student)
}

func main() {
    students := []string{}
    result := addStudent[string](students, "Michael")
    result = addStudent[string](result, "Jennifer")
    result = addStudent[string](result, "Elaine")
    fmt.Println(result)

    students1 := []int{}
    result1 := addStudent[int](students1, 45)
    result1 = addStudent[int](result1, 64)
    result1 = addStudent[int](result1, 78)
    fmt.Println(result1)

    students2 := []Student{}
    result2 := addStudent[Student](students2, Student{"John", 213, 17.5})
    result2 = addStudent[Student](result2, Student{"James", 111, 18.75})
    result2 = addStudent[Student](result2, Student{"Marsha", 110, 16.25})
    fmt.Println(result2)
}
posted on 2022-12-21 15:21  北京涛子  阅读(218)  评论(0)    收藏  举报