我正在通过修改我为处理切片而创建的库来尝试泛型。我有一个Difference函数,它接受切片并返回仅在其中一个切片中找到的唯一元素的列表。
我修改了该函数以使用泛型,并且我正在尝试使用不同类型(例如字符串和整数)编写单元测试,但在联合类型方面遇到了麻烦。这就是我现在所拥有的:
\ntype testDifferenceInput[T comparable] [][]T\ntype testDifferenceOutput[T comparable] []T\ntype testDifference[T comparable] struct {\n input testDifferenceInput[T]\n output testDifferenceOutput[T]\n}\n\nfunc TestDifference(t *testing.T) {\n for i, tt := range []testDifference[int] {\n testDifference[int]{\n input: testDifferenceInput[int]{\n []int{1, 2, 3, 3, 4},\n []int{1, 2, 5},\n []int{1, 3, 6},\n },\n output: []int{4, 5, 6},\n },\n } {\n t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {\n actual := Difference(tt.input...)\n\n if !isEqual(actual, tt.output) {\n t.Errorf("expected: %v %T, received: %v %T", tt.output, tt.output, actual, actual)\n }\n …Run Code Online (Sandbox Code Playgroud) 使用 Go 1.18 中的新泛型,我认为可以创建一个“Either[A,B]”类型,该类型可用于表达某物可以是 A 类型或 B 类型。
您可能会使用此功能的情况是函数可能返回两个可能值之一作为结果(例如,一个表示“正常”结果,一个表示错误)。
我知道 Go 处理错误的“惯用”方式是返回“正常”值和错误值,对于错误或值返回 nil。但是……让我有点困扰的是,我们本质上是在类型中说“这返回 A和B”,而我们真正想说的是“这返回 A或B”。
所以我想也许我们可以在这里做得更好,我认为这也可能是一个很好的练习,可以看到/测试我们可以用这些新泛型做的事情的界限。
可悲的是,尽我所能,到目前为止我还没有能够解决这个练习并让任何东西工作/编译。从我一次失败的尝试来看,这是一个我想以某种方式实现的接口:
//A value of type `Either[A,B]` holds one value which can be either of type A or type B.
type Either[A any, B any] interface {
// Call either one of two functions depending on whether the value is an A or B
// and return the result.
Switch[R any]( // <=== ERROR: interface methods must have no …Run Code Online (Sandbox Code Playgroud)