"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can Go language implement interface anonymously?

Can Go language implement interface anonymously?

Posted on 2025-04-18
Browse:890

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.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3