Home > other >  An interface with methods as type constraint for generic function
An interface with methods as type constraint for generic function

Time:02-02

I am trying to make use of generics when writing an asserting function for testing things however it gives me an error Some does not implement TestUtilT (wrong type for method Equals...) error. How can I make code bellow work if at all?

package test_util

import (
    "fmt"
    "testing"
)

type TestUtilT interface {
    Equals(TestUtilT) bool
    String() string
}

func Assert[U TestUtilT](t *testing.T, location string, must, is U) {
    if !is.Equals(must) {
        t.Fatalf("%s expected: %s got: %s\n",
            fmt.Sprintf("[%s]", location),
            must,
            is,
        )
    }
}

type Some struct {
}

func (s *Some) Equals(other Some) bool {
    return true
}

func (s *Some) String() string {
    return ""
}

func TestFunc(t *testing.T) {
    Assert[Some](t, "", Some{}, Some{}) 
    // Error: "Some does not implement TestUtilT (wrong type for method Equals...)"

}

CodePudding user response:

Replace

func (s *Some) Equals(other Some) bool {

with

func (s *Some) Equals(other TestUtilT) bool {

Then replace

Assert[Some](t, "", Some{}, Some{})

with

Assert[Some](t, "", &Some{}, &Some{})

The first change will fix your initial error message, but your code will still not work without the second change as well.

  • Related