Home >Backend Development >Golang >Can Go Implement Anonymous Interfaces?

Can Go Implement Anonymous Interfaces?

DDD
DDDOriginal
2024-11-27 03:44:16884browse

Can Go Implement Anonymous Interfaces?

Is Anonymous Interface Implementation Possible in Go?

Consider the following interface and a function from an imaginary library:

type NumOp interface {
    Binary(int, int) int
    Ternary(int, int, int) int
}

func RandomNumOp(op NumOp) {
    // ...
}

To implement this interface, one could define a type like:

type MyAdd struct {}
func (MyAdd) Binary(a, b int) int {return a + b }
func (MyAdd) Ternary(a, b, c int) int {return a + b + c }

Need for a Functional Implementation

However, suppose we need to implement the interface using anonymous functions for single-use scenarios. This would allow us to write:

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

Implementation Restrictions

Unfortunately, in Go, method declarations must reside at the file level. To implement an interface with multiple methods, these declarations are required.

Workable Implementation

If a working implementation is necessary, you can use a dummy implementation:

type DummyOp struct{}

func (DummyOp) Binary(_, _ int) int     { return 0 }
func (DummyOp) Ternary(_, _, _ int) int { return 0 }

Dynamic Partial Implementation

To set some methods dynamically, consider a delegator struct:

type CustomOp struct {
    binary  func(int, int) int
    ternary func(int, int, int) int
}

func (cop CustomOp) Binary(a, b int) int {
    // ...
}

func (cop CustomOp) Ternary(a, b, c int) int {
    // ...
}

Non-Functional Implementation

If the methods don't need to be callable, you can use an anonymous struct literal:

var op NumOp = struct{ NumOp }{}

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