Home >Backend Development >Golang >How to Handle Generic Functions with Interface-Implementing Pointers in Go?

How to Handle Generic Functions with Interface-Implementing Pointers in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-31 01:28:09977browse

How to Handle Generic Functions with Interface-Implementing Pointers in Go?

Generic Type for Interface-Implementing Pointer

In Go, creating a generic function that takes in a function with an interface parameter can be challenging when the implementation of that interface is a pointer to a struct.

Consider the following interface:

type A interface {
  SomeMethod()
}

We have an implementation of this interface as a struct pointer:

type Aimpl struct {}

func (a *Aimpl) SomeMethod() {}

We want to define a generic function that takes in a function with an A parameter:

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, the error arises because result does not implement the interface; it's a pointer to a type, not the type itself.

Solution 1: Interface with Type Parameter

To resolve this, we can declare the interface with a type parameter, requiring that the type implementing it be a pointer to its type parameter:

type A[P any] interface {
    SomeMethod()
    *P
}

With this modification, the handler's signature needs to be adjusted:

func Handler[P any, T A[P]](callback func(result T)) {
    result := new(P)
    callback(result)
}

Solution 2: Wrapper Interface

If modifying the definition of A is not an option, we can create a wrapper interface:

type MyA[P any] interface {
    A
    *P
}

And modify the handler's signature accordingly:

func Handler[P any, T MyA[P]](callback func(result T)) {
    result := new(P)
    callback(result)
}

The above is the detailed content of How to Handle Generic Functions with Interface-Implementing Pointers in Go?. 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