Generic Pointer to Interface Implementation
In Go, defining a generic function that accepts a pointer to an interface can be challenging. Consider an interface A with a SomeMethod():
type A interface { SomeMethod() }
And suppose there's an implementation of A as a struct pointer:
type Aimpl struct {} func (a *Aimpl) SomeMethod() {}
To create a generic function Handler that takes a function with an A parameter, it would be desirable to define:
func Handler[T A](callback func(result T)) { // Essentially what I'd like to do is result := &Aimpl{} (or whatever T is) callback(result) }
However, there are some constraints to consider.
Attempt with any Type Parameter
Initially, it may seem possible to define an interface with a type parameter to allow pointer implementations:
type MyA[T any] interface{ A *T }
However, this fails with the following error:
result does not implement interface. It's a pointer to a type, not a type
Solution: Type Parameterized Interface
To overcome this, the interface can be declared with a type parameter that requires the implementing type to be a pointer to its type parameter:
type A[P any] interface { SomeMethod() *P }
With this interface, the Handler function can be modified:
func Handler[P any, T A[P]](callback func(result T)) { result := new(P) callback(result) }
Now, the code can call Handler as expected:
Handler(func(a *Aimpl) { fmt.Printf("%#v\n", a) })
Alternative with Interface Wrapper
If the definition of A cannot be modified, an alternative approach is to wrap it in a custom interface:
type MyA[P any] interface { A *P }
And modify the Handler function accordingly:
func Handler[P any, T MyA[P]](callback func(result T)) { result := new(P) callback(result) }
Both solutions allow for the creation of generic functions that accept pointers to interface implementations.
The above is the detailed content of How Can I Create a Generic Go Function That Accepts a Pointer to an Interface Implementation?. For more information, please follow other related articles on the PHP Chinese website!