Go Mastery: A Comprehensive Guide - Part 4: Structs and Interfaces
Go Mastery: A Comprehensive Guide - Part 4: Structs and Interfaces
Introduction
Go is not a traditional object-oriented language like Java or C++. Instead, it uses Structs for data modeling and Interfaces for abstraction and polymorphism. This approach is more flexible, readable, and idiomatic.
Structs: Data Modeling
A struct is a collection of fields.
1
2
3
4
5
6
7
8
type User struct {
ID int
Name string
Email string
}
// Creating an instance
u := User{ID: 1, Name: "Alice", Email: "alice@example.com"}
You can define methods on structs:
1
2
3
func (u User) Greeting() string {
return "Hello, " + u.Name
}
Interfaces: Abstraction
An interface defines a set of methods that a type must implement. Go’s interfaces are satisfied implicitly. If a type implements all the methods defined in an interface, it is said to satisfy that interface.
1
2
3
4
5
6
7
type Greeter interface {
Greeting() string
}
func SayHello(g Greeter) {
fmt.Println(g.Greeting())
}
Conclusion
Structs allow you to define clear data structures, while interfaces enable powerful polymorphism without complex class hierarchies. These building blocks are foundational for writing modular, testable, and maintainable Go applications.
Suggested Reading
This post is licensed under
CC BY 4.0
by the author.