How to Define and Implement an Interface in Go

Define a Go interface by listing method signatures and implement it by adding those methods to a type, which Go recognizes automatically.

Define an interface by declaring a set of method signatures, then implement it by adding those exact methods to a type. Go interfaces are satisfied implicitly; if a type has the required methods, it implements the interface without explicit declaration.

// Define the interface
type Hasher interface {
	Sum32() uint32
	Sum64() uint64
}

// Implement the interface
type MyHash struct {
	data []byte
}

func (h *MyHash) Sum32() uint32 { return 0 }
func (h *MyHash) Sum64() uint64 { return 0 }

// Usage: MyHash automatically implements Hasher
var h Hasher = &MyHash{data: []byte("test")}