Can Go Implement Interfaces Anonymously?

Patricia Arquette
Release: 2024-11-25 22:29:11
Original
346 people have browsed it

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

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!

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