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

Interface with type constraints for methods as generic functions

王林
Release: 2024-02-06 09:45:11
forward
981 people have browsed it

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

}
Copy after login


Correct answer


Replace

func (s *some) equals(other some) bool {
Copy after login

and

func (s *some) equals(other testutilt) bool {
Copy after login

Then replace

assert[some](t, "", some{}, some{})
Copy after login

and

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template