Understanding Structs and Interfaces in Go

When learning Go (Golang), two of the most important concepts you’ll encounter are structs and interfaces. They form the foundation of how Go handles data modeling, abstraction, and dependency management.
In this tutorial, we’ll start with the basics of structs and interfaces, then show how they combine in real-world projects.
Structs in Go
🔗A struct is a custom data type that groups related fields together. You can also attach methods to it.
gotype User struct {
ID int
Name string
Email string
}
func (u *User) Greet() {
fmt.Printf("Hello, my name is %s!\n", u.Name)
}
Interfaces in Go
🔗An interface defines a set of methods. Any type that implements these methods automatically satisfies the interface.
gotype Greeter interface {
Greet()
}
type User struct {
Name string
}
func (u User) Greet() {
fmt.Printf("Hi, I'm %s!\n", u.Name)
}
type Robot struct {
Model string
}
func (r Robot) Greet() {
fmt.Printf("Beep boop, I am robot %s!\n", r.Model)
}
Interfaces in Real Projects
🔗In real-world applications, we don’t just use structs and interfaces in isolation. A common industry pattern is to define interfaces as contracts and structs as implementations.
Example (simplified repository contract):
go// UserRepository defines how we interact with user data.
type UserRepository interface {
GetUserByID(id int) (*User, error)
CreateUser(user *User) error
}
With this setup, you can:
- Swap database backends (Postgres, MySQL, MongoDB)
- Mock the repository in tests
But how does this fit into a full layered architecture (Handler → Service → Repository → Database)? That’s where we move to the next tutorial.
Next Step
🔗If you’re comfortable with structs and interfaces, continue to:
➡️ Layered Architecture in Go: Structs and Interfaces in Action

Alvin
Software engineer, interested in financial knowledge, health concepts, psychology, independent travel, and system design.