~/Go Interfaces Explained

Sep 14, 2025


First read the official interface documentation to understand the interface construct in the Go language.

Interface Value

An interface in Go is a type that specifies zero or more method signatures. Any type that implements those methods implicitly implements the interface, without requiring explicit declaration, unlike languages like Java. Go uses structural typing, not nominal typing.

Purpose of Interfaces

The main points of interfaces are:

Getting Real: Repository Pattern Example

Suppose you need an object for storing and fetching users. In-memory or SQL both satisfy these contracts.

1
2
3
4
5
6
7
8
9
type User struct {
    ID   int
    Name string
}

type UserRepository interface {
    Save(user User) error
    Find(id int) (User, error)
}

You might create an in memory version:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
type MemoryUserRepo struct {
    users map[int]User
}

func (m *MemoryUserRepo) Save(user User) error {
    m.users[user.ID] = user
    return nil
}

func (m *MemoryUserRepo) Find(id int) (User, error) {
    user, found := m.users[id]
    if !found {
        return User{}, fmt.Errorf("not found")
    }
    return user, nil
}

and a SQL version:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
type SQLUserRepo struct {
    db *sql.DB
}

func (s *SQLUserRepo) Save(user User) error {
    // simplified query
    _, err := s.db.Exec("INSERT INTO users (id, name) VALUES (?, ?)", user.ID, user.Name)
    return err
}

func (s *SQLUserRepo) Find(id int) (User, error) {
    row := s.db.QueryRow("SELECT id, name FROM users WHERE id = ?", id)
    var user User
    err := row.Scan(&user.ID, &user.Name)
    return user, err
}

Now you can write code that works with any UserRepository, abstracting away implementation:

1
2
3
func registerUser(repo UserRepository, user User) error {
    return repo.Save(user)
}

Benefits

Trivia

Adjacent Patterns and Misuses

See also Effective Go interfaces and A Tour of Go: Interfaces.

Related Reading

This summary should clarify the contract, polymorphism, and practical motivation of Go interfaces.

Tags: [go] [interfaces] [patterns] [repository] [programming]