Home > Backend Development > Golang > How to Create a Generic Type for a Pointer Implementing an Interface in Go?

How to Create a Generic Type for a Pointer Implementing an Interface in Go?

Linda Hamilton
Release: 2024-12-29 20:40:18
Original
401 people have browsed it

How to Create a Generic Type for a Pointer Implementing an Interface in Go?

Generic Type for a Pointer Implementing an Interface

When working with interfaces in Go, it may be necessary to pass in a pointer to a struct that implements the interface. This can be challenging when defining generic functions.

Question:

How can I create a generic type for a pointer that implements an interface?

Answer:

Option 1: Modify the Interface Definition

  1. Declare the interface with a type parameter to specify that its implementing type must be a pointer to its type parameter:
  1. Modify the handler's signature:

Option 2: Wrap the Interface (If Modifying Definition is Not Possible)

  1. Create a wrapper interface that embeds the original interface and adds a pointer to its type parameter:
  1. Modify the handler's signature to accept the wrapped interface:

Usage:

Both options allow passing a pointer to a struct that implements the A interface to the generic function Handler. For example:

The above is the detailed content of How to Create a Generic Type for a Pointer Implementing an Interface 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