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
Release: 2024-12-31 01:28:09
Original
963 people have browsed it

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()
}
Copy after login

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

type Aimpl struct {}

func (a *Aimpl) SomeMethod() {}
Copy after login

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)
}
Copy after login

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
}
Copy after login

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)
}
Copy after login

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
}
Copy after login

And modify the handler's signature accordingly:

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

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!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template