Home >Backend Development >Golang >Can Anonymous Interface Implementations Be Achieved in Go?
Go allows for the definition of custom types using interfaces. However, it raises the question of whether it's possible to establish an anonymous implementation of an interface for situations where specific functions need to be implemented as simple operations.
The pseudo code provided suggests creating an anonymous implementation similar to:
RandomNumOp({ Binary: func(a, b int) int { return a + b }, Ternary: func(a, b, c int) int { return a + b + c }, })
However, this approach is not directly feasible in Go because method declarations must be defined at the file level. Therefore, to implement an interface with multiple methods, explicit method declarations are necessary.
To obtain a workable implementation, you can utilize an existing struct or create a "dummy" implementation to emphasize the lack of consequences. Here's an example:
type DummyOp struct{} func (DummyOp) Binary(_, _ int) int { return 0 } func (DummyOp) Ternary(_, _, _ int) int { return 0 }
Alternatively, consider a delegator struct type that allows you to dynamically provide functions for the methods:
type CustomOp struct { binary func(int, int) int ternary func(int, int, int) int } func (cop CustomOp) Binary(a, b int) int { if cop.binary != nil { return cop.binary(a, b) } return 0 } func (cop CustomOp) Ternary(a, b, c int) int { if cop.ternary != nil { return cop.ternary(a, b, c) } return 0 }
Example usage:
RandomNumOp(CustomOp{ binary: func(a, b int) int { return a + b }, })
If your implementation does not require functional methods, you can use an anonymous struct literal:
var op NumOp = struct{ NumOp }{}
The above is the detailed content of Can Anonymous Interface Implementations Be Achieved in Go?. For more information, please follow other related articles on the PHP Chinese website!