Home >Backend Development >Golang >How Can Generics in Go Handle Functions with Pointer-Based Interface Parameters?

How Can Generics in Go Handle Functions with Pointer-Based Interface Parameters?

Barbara Streisand
Barbara StreisandOriginal
2024-12-29 00:36:09114browse

How Can Generics in Go Handle Functions with Pointer-Based Interface Parameters?

Generic Interface of Pointers

In Go, defining an interface for a pointer implementation can be done through generics. Consider the following scenario:

Problem:

  • You have an interface A with a method SomeMethod().
  • You have a struct pointer *Aimpl that implements the A interface.
  • You want to create a generic function Handler that accepts a function with an A parameter, and assigns a pointer to Aimpl to its parameter.

Solution Using Generic Interface with Type Parameter:

To achieve this, you can declare the A interface with a type parameter, ensuring that the implementing type is a pointer to its type parameter:

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

Then, modify the signature of Handler as follows:

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

Solution Using Wrapper Interface:

If you cannot modify the definition of A, you can wrap it into your own interface MyA:

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

Then, update the signature of Handler to use the MyA interface:

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

The above is the detailed content of How Can Generics in Go Handle Functions with Pointer-Based Interface Parameters?. 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