Skip to content

泛型

泛型函数

如果我们要实现一个对 int 类型的求和函数

go
func add(a, b int) int {
  return a + b
}

但是这样写了之后,如果参数是 float 类型,int32 类型这些,就没办法使用了

难道要为每个类型都写一个这样的函数吗?

显然这就不合理

这个时候,泛型就上场了

go
func add[T int | float64 | int32](a, b T) T {
  return a + b
}

泛型结构体

go
package main

import (
  "encoding/json"
  "fmt"
)

type Response[T any] struct {
  Code int    `json:"code"`
  Msg  string `json:"msg"`
  Data T      `json:"data"`
}

func main() {
  type User struct {
    Name string `json:"name"`
  }

  type UserInfo struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
  }

  //user := Response{
  //  Code: 0,
  //  Msg:  "成功",
  //  Data: User{
  //    Name: "枫枫",
  //  },
  //}
  //byteData, _ := json.Marshal(user)
  //fmt.Println(string(byteData))
  //userInfo := Response{
  //  Code: 0,
  //  Msg:  "成功",
  //  Data: UserInfo{
  //    Name: "枫枫",
  //    Age:  24,
  //  },
  //}
  //byteData, _ = json.Marshal(userInfo)
  //fmt.Println(string(byteData))

  var userResponse Response[User]
  json.Unmarshal([]byte(`{"code":0,"msg":"成功","data":{"name":"枫枫"}}`), &userResponse)
  fmt.Println(userResponse.Data.Name)
  var userInfoResponse Response[UserInfo]
  json.Unmarshal([]byte(`{"code":0,"msg":"成功","data":{"name":"枫枫","age":24}}`), &userInfoResponse)
  fmt.Println(userInfoResponse.Data.Name, userInfoResponse.Data.Age)
}

泛型切片

go
package main

type MySlice[T any] []T

func main() {
  var mySlice MySlice[string]
  mySlice = append(mySlice, "枫枫")
  var intSlice MySlice[int]
  intSlice = append(intSlice, 2)
}

泛型 map

go
package main

import "fmt"

type MyMap[K string | int, V any] map[K]V

func main() {
  var myMap = make(MyMap[string, string])
  myMap["name"] = "枫枫"
  fmt.Println(myMap)
}