Interfaces

Consumer-defined interfaces

Define an interface at the consumer boundary when it needs a small behavior contract. Implementations and test doubles can satisfy that contract independently. Prefer concrete types when no abstraction is required. Example output: '8'.

Formal Syntax & Structure

go syntaxgo
type Source interface { Value() int }

Working Example

Example Snippetgo
package main
import "fmt"
type Source interface{ Value() int }type fixed int
func (f fixed) Value() int { return int(f) }func total(s Source) int   { return s.Value() * 2 }func main() {  fmt.Println(total(fixed(4)))}
Go Reference