golang 接口方法使用泛型
在 Go 语言中,从 Go 1.18 开始支持泛型,这使得接口可以定义使用泛型的方法。泛型允许你编写灵活且可重用的组件,这些组件能够处理多种类型而无需为每种类型重复代码。
下面是一个简单的例子来展示如何定义一个使用泛型的接口方法:
Go
package main
import (
"fmt"
"reflect"
)
// 定义一个空接口 Numeric,它可以接受 int 和 float64
type Numeric interface{}
// 定义一个使用泛型的接口
type GenericInterface[T Numeric] interface {
SetValue(T)
GetValue() T
}
// 实现泛型接口的结构体
type MyStruct[T Numeric] struct {
Value T
}
// 定义一个泛型构造函数
func NewMyStruct[T Numeric](value T) MyStruct[T] {
return MyStruct[T]{Value: value}
}
// 泛型方法实现
func (m *MyStruct[T]) SetValue(value T) {
m.Value = value
}
func (m *MyStruct[T]) GetValue() T {
return m.Value
}
func main() {
// 创建不同类型的实例
intInstance := NewMyStruct[int](10)
floatInstance := NewMyStruct[float64](10.5)
// 使用整数实例
fmt.Printf("Integer Value: %v, Type: %s\n", intInstance.Value, reflect.TypeOf(intInstance.Value))
intInstance.SetValue(109)
// 使用整数实例
fmt.Printf("Integer Value: %v, Type: %s\n", intInstance.GetValue(), reflect.TypeOf(intInstance.GetValue()))
// 使用浮点数实例
fmt.Printf("Float Value: %v, Type: %s\n", floatInstance.Value, reflect.TypeOf(floatInstance.Value))
}

