最少的内容简述如何在GO中使用泛型编程
函数泛型
func f[T any](s Set[T]) {}
在函数声明的时候添加一个
[]
作为泛型的说明, 在使用的时候是可以自动推断
- 很多时候, any的类型声明可能导致缺失一些条件, 比如不能比较大小, 所以无法使用
结构体泛型
type SetDataType interface {comparable
}type Set[T SetDataType] struct {data map[T]bool
}
使用map需要其中的元素的类型是可以比较的(即需要实现comparable接口)
使用结构体的时候必须指出对应的类型, 例如Set[string]
才可以使用
Set[T]
是完整的类型名字, 在结构体的方法实现的时候需要使用完整的名字
接口泛型
type Inter[T any] interface {comparable
}
泛型约束
func f[T int | string](s Set[T]) {}
可以限制泛型的类型是在几种类型之间的
泛型命名
type Type interface {int | string | float64
}
给需要使用的泛型的可能情况取名字
type Type interface {int | string | float64error
}
可以指定泛型需要实现的接口