在GO 1.18中引入的GO
go的通用物中,如何将仿制药与接口一起使用,从而显着增强了接口的功率和灵活性。 您可以使用仿制药来创建在各种具体类型上运行的功能和类型,同时仍利用基于接口的多态性的好处。 关键是要在您的通用函数或类型签名中定义类型参数,从而允许将这些参数限制在特定的接口。让我们用示例说明。假设您需要一个在切片中找到最大元素的函数,无论该元素的基础类型如何,只要它实现a
>接口:Comparable
package main import ( "fmt" ) type Comparable interface { Less(other interface{}) bool } func Max[T Comparable](slice []T) T { if len(slice) == 0 { var zero T return zero // Handle empty slice } max := slice[0] for _, v := range slice { if v.Less(max) { max = v } } return max } type Int int func (i Int) Less(other interface{}) bool { return i < other.(Int) } type String string func (s String) Less(other interface{}) bool { return s < other.(String) } func main() { intSlice := []Int{1, 5, 2, 8, 3} stringSlice := []String{"banana", "apple", "orange"} maxInt := Max(intSlice) maxString := Max(stringSlice) fmt.Println("Max int:", maxInt) // Output: Max int: 8 fmt.Println("Max string:", maxString) // Output: Max string: orange }
>>> Max
> T
函数使用类型parameter Comparable
受Less
接口约束的类型。 Comparable
接口中的
使用仿制药,您可以编写一个单个功能或类型,该功能与任何满足特定接口约束的类型一起使用。 这大大降低了冗余。 上面的Max
示例完美地展示了以下内容:一个Max
函数适用于Int
>,String
,或任何其他实现Comparable
>接口的其他类型,消除了对单独的MaxInt
,MaxString
等的需求。 这种增加的可重复性会导致更清洁,更可维护且较少易于错误的代码库。
以上是如何将仿制药与插入中的接口使用?的详细内容。更多信息请关注PHP中文网其他相关文章!