使用空接口在"generic"代码中强制实施类型



很抱歉标题模棱两可。

我 http://algs4.cs.princeton.edu/home/读这本书,我认为在 Go 中实现示例作为学习练习会很好,但是这本书使用 Java 作为描述代码的语言。

第一章之一讨论了设置一些核心数据类型/容器样式类以便以后重用,但我在尝试将它们锤炼到 Go 设置中时遇到了麻烦,主要是因为这些数据类型似乎喜欢使用 Java 泛型。

例如,我编写了以下代码

package bag
type T interface{}
type Bag []T
func (a *Bag) Add(t T) {
    *a = append(*a, t)
}
func (a *Bag) IsEmpty() bool {
    return len(*a) == 0
}
func (a *Bag) Size() int {
    return len(*a)
}

这原则上是有效的,因为我可以将项目添加到Bag并检查其大小和所有内容。但是,这也意味着以下代码是合法的

a := make(bag.Bag,0,0)
a.Add(1)
a.Add("Hello world!")
a.Add(5.6)
a.Add(time.Now())

我只是想知道是否有任何方法可以强制执行该类型,使其符合类似于

Bag<T> bagOfMyType = new Bag<T>()

例如

Bag<Integer> bagOfInts = new Bag<Integer>()

我知道 Go 没有泛型,它们也不是真正的 Go Way,但我只是想知道是否有可能在编译时"强制执行"任何东西(可能不是)

对不起,长帖子

编辑:好的,所以我一直在进一步研究这个问题,我几乎已经放弃了泛型方面的事情(我知道这不在 Go 的路线图上),所以我正在考虑做一些类似于带有接口的 Haskell 类型类的事情,例如

type T interface{}
type Bag interface {
    Add(t T)
    IsEmpty() bool
    Size() int
}
type IntSlice []int
func (i *IntSlice) Add(t T) {
    *i = append(*i, t.(int)) // will throw runtime exception if user attempts to add anything other than int
}
func (i *IntSlice) IsEmpty() bool {
    return len(*i) == 0
}
func (i *IntSlice) Size() int {
    return len(*i)
}

这样做的问题是类型强制仅在运行时强制执行。

有人有任何想法如何改进这一点吗?

我自己是 Go 的新手,所以我很好奇是否有人会有更好的答案,但这是我的看法:

您希望编译时强制在IntSlice上调用Add()时,其参数为int。 好吧,这是你如何做到这一点的:

func (i *IntSlice) Add(t int) {
    *i = append(*i, t)
}

由于没有泛型,因此每种类型的BagAdd()方法都会有所不同,因此Bag接口(假设您需要它)变为:

type Bag interface {
    IsEmpty() bool
    Size() int
}

这对我来说是有道理的,因为你不能把Bag传来传去,然后把任何东西扔进去。 知道某件事是Bag并不足以知道如何打电话给Add();您必须知道您正在处理的Bag类型。

您可以使接口特定于该类型,例如 IntBag ,但由于实际上只有一个类型可以满足该接口,因此您不妨摆脱该接口并将IntSlice的名称更改为 IntBag

基本上,这意味着完全放弃任何类似泛型的东西,而只是使用一些方法创建一个类型来做你想要的事情:

type IntBag []int
func (b *IntBag) Add(i int) {
    *b = append(*b, i)
}
func (b IntBag) IsEmpty() bool {
    return len(b) == 0
}
func (b IntBag) Size() int {
    return len(b)
}

更新:有时泛型真的会派上用场。 在我看来,我们只能根据具体情况选择最适合给定问题的方法。 使用空接口和反射,您可以获得一些类似泛型的行为,但它往往很丑陋,并且您放弃了一些编译时类型检查。 或者你放弃泛型并有一些代码重复。或者你只是用完全不同的方式去做。

几周前我问了一个问题,关于我应该如何使用 Go 来处理在我看来需要类层次结构的问题。答案基本上是没有通用的解决办法;这都是个案的。我认为这同样适用于泛型:Go 中没有泛型,也没有将基于泛型的解决方案转换为 Go 的通用解决方案。

在很多情况下,你可能会使用另一种语言的泛型,但在 Go 中界面是完全足够的(或真正闪耀的)。 您在此处的示例是接口实际上不是正确替代品的示例。 另请参阅:Go Vs. 泛型。

我非常精通 Go。泛型是一个备受争议的话题,目前没有类似于Java泛型或C++模板的东西。目前的约定是实现具有空接口的"泛型"类型,然后将其包装为特定类型实现,以确保仅使用该类型的元素。下面是一个来自 Go 标准库container/list的示例。

http://play.golang.org/p/9w9H1EPHKR

package main
import (
    "container/list"
    "fmt"
)
type IntList struct {
    innerList *list.List
}
func NewIntList() *IntList {
    return &IntList{list.New()}
}
func (l *IntList) Add(i int) {
    // this is the only way to add an element to the list,
    // and the Add() method only takes ints, so only ints
    // can be added
    l.innerList.PushBack(i)
}
func (l *IntList) Last() int {
    lastElem := l.innerList.Back()
    // We can safely type-assert to an int, because Add()
    // guarantees that we can't put a non-int into our list
    return lastElem.Value.(int)
}
func main() {
    l := NewIntList()
    l.Add(5)
    l.Add(4)
    l.Add(3)
    l.Add(2)
    l.Add(1)
    fmt.Println("Expecting 1; got:", l.Last())
}

Go 现在支持泛型(从 1.18 版本开始): https://go.dev/doc/tutorial/generics

下面是基于问题中示例的插图:

import "time"
type Bag[T any] []T
func (a *Bag[T]) Add(t T) {
    *a = append(*a, t)
}
func (a *Bag[T]) IsEmpty() bool {
    return len(*a) == 0
}
func (a *Bag[T]) Size() int {
    return len(*a)
}
func main() {
    indiscriminateBag := make(Bag[any], 0, 0)
    indiscriminateBag.Add(1)
    indiscriminateBag.Add("Hello world!")
    indiscriminateBag.Add(5.6)
    indiscriminateBag.Add(time.Now())
    selectiveBag := make(Bag[int], 0, 0)
    selectiveBag.Add(1)
    selectiveBag.Add(1.25) // Compiler complains: cannot use 1.25 (untyped float constant) as int value in argument to selectiveBag.Add
}

我在这里添加这个答案,以防万一其他刚接触 Go 的人偶然发现了这个问题。

顺便说一下,我也开始考虑 Go 泛型,同时在 Go 中实施普林斯顿算法课程。以下是一些通用符号表

最新更新