Home >Backend Development >Golang >Can Anonymous Interface Implementations Be Achieved in Go?

Can Anonymous Interface Implementations Be Achieved in Go?

DDD
DDDOriginal
2024-11-26 18:35:13192browse

Can Anonymous Interface Implementations Be Achieved in Go?

Anonymous Interface Implementation in Go

Introduction

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.

Anonymous Implementation with Functions

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 },
})

Limitations

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.

Workable Implementation

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 },
})

Non-Functional Implementation

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!

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