Home  >  Article  >  Backend Development  >  Can Go Implement Interfaces Anonymously?

Can Go Implement Interfaces Anonymously?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-25 22:29:11346browse

Can Go Implement Interfaces Anonymously?

Is Anonymous Interface Implementation Possible in Go?

The ability to define an anonymous implementation of an interface using anonymous functions, similar to the pseudo code:

RandomNumOp({
   Binary: func(a,b int) int { return a+b},
   Ternary: func(a,b,c int) int {return a+b+c},
})

is not directly supported in Go. Here are some possible approaches, depending on whether the implementation is required to work:

If Implementation Must Work

  • Use an Existing Implementation: Define a type that embeds an existing implementation, providing the required methods.

If Implementation Is Not Required to Work

  • Use an Anonymous Struct Literal: Embed the interface type in an anonymous struct literal, providing a placeholder implementation (with empty methods) for the interface functions.

The above is the detailed content of Can Go Implement Interfaces Anonymously?. 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