Home >Backend Development >Golang >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:
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!