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

Can Go Implement Anonymous Interfaces?

DDD
Release: 2024-11-27 03:44:16
Original
885 people have browsed it

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) {
    // ...
}
Copy after login

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

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

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

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 {
    // ...
}
Copy after login

Non-Functional Implementation

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

var op NumOp = struct{ NumOp }{}
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template