NOTE

Function Types as Interfaces

What an interface function is, why it is useful, and a Go implementation that allows either function values or structs to satisfy the same interface.

Software Architecture & EngineeringCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What Is an Interface Function?

A function type that implements an interface, referred to as an interface function.

2. Why Are Interface Functions Needed?

They allow both ordinary function types (after type conversion) and structs to be passed as parameters. This is more flexible and also more readable, which is the value of interface functions.

3. Implementation

//1.
// Define the Getter interface
// Query data by key
type Getter interface {
	Get(key string) ([]byte, error)
}

//2.
// Define the GetterFunc function type
type GetterFunc func(key string) ([]byte, error)

// GetterFunc implements the Getter interface
func (f GetterFunc) Get(key string) ([]byte, error) {
	return f(key)
}

//3.
// Get a result from a data source
// The Getter interface is one parameter and represents a data source
func GetFromSource(getter Getter, key string) []byte {
	buf, err := getter.Get(key)
	if err == nil {
		return buf
	}
	return nil
}

//4.
// Get data from the database
func getFromDB(key string) ([]byte, error) {
	return []byte(key), nil
}

//4.
// Get data from Redis
// Implements the Getter interface
type Redis struct {
}

func (r *Redis) Get(key string) ([]byte, error) {
	return []byte(key), nil
}
func TestIFunc(t *testing.T) {
	// The first argument to GetFromSource can be a function
	// GetterFunc(getFromDB) is an explicit type conversion here
	GetFromSource(GetterFunc(getFromDB), "hello")
	// The first argument to GetFromSource can also be a struct
	GetFromSource(new(Redis), "hello")

}

4. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub