How to declare a method of generic pointer interface or slice pointer interface parameters

0

eg:

type AnyPtr[T any] interface {
    *T
}

type AnyPtrSlice[T any] interface {
    []*T
}

func FuncName[T AnyPtr[E] | AnyPtrSlice[E], E any](data T) (err error) {
}


type ModelAA struct {
    A int
    B int
}

func TestAddV2(t *testing.T) {
    var a = ModelAA{
        A: 1, B: 2,
    }
    _ = FuncName(&a)
}

This approach will be reported by the compiler as being unable to infer E. Is there any other way to write it?

Hi @wake2012, welcome to the forum.

Maybe you need the two Any* interfaces for some reason that is not apparent from the code snippet, but I have removed them to simplify the code. Within the context of the given code, the following function signature is semantically identical to your definition using the Any* interfaces:

func FuncName[T *E | []*E, E any](data T) (err error)

The error message seems unjustified, as the type of &a is clearly “pointer to ModelAA” and not “slice of pointers to ModelAA”. But you can help the compiler and specify the types to use for T and E when calling the function:

package main

import "testing"

func FuncName[T *E | []*E, E any](data T) (err error) {
	return nil
}

type ModelAA struct {
	A int
	B int
}

func TestAddV2(t *testing.T) {
	var a = ModelAA{
		A: 1, B: 2,
	}
	_ = FuncName[*ModelAA, ModelAA](&a)
}

(Run the code in the Go Playground)

(See also Type inferrence in the langugage specification)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.