Home >Backend Development >Golang >Interface with type constraints for methods as generic functions

Interface with type constraints for methods as generic functions

王林
王林forward
2024-02-06 09:45:11978browse

Interface with type constraints for methods as generic functions

Question content

I am trying to use generics while writing an assertion function to test things, but it gives me an errorsome does not implement testutilt (wrong type for method equals...) Error. If so how can I make the code below work?

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...)"

}

Correct answer


Replace

func (s *some) equals(other some) bool {

and

func (s *some) equals(other testutilt) bool {

Then replace

assert[some](t, "", some{}, some{})

and

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

The first change will fix your initial error message, but your code still won't work without the second change.

The above is the detailed content of Interface with type constraints for methods as generic functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete