Home >Backend Development >Golang >How Can I Create a Generic Go Function That Accepts a Pointer to an Interface Implementation?

How Can I Create a Generic Go Function That Accepts a Pointer to an Interface Implementation?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-21 05:25:14185browse

How Can I Create a Generic Go Function That Accepts a Pointer to an Interface Implementation?

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!

Statement:
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