Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
22: Interfaces in Go
I've seen this exact mistake a dozen times with engineers moving to Go from Java or C#. They try to treat Go slices like they treat generic lists in other languages, and they run straight into a compiler error that feels totally illogical at first glance.
package main
import "fmt"
type PaymentMethod interface {
Pay(amount float64) string
}
type CreditCard struct {
CardNumber string
}
func (cc CreditCard) Pay(amount float64) string {
return fmt.Sprintf("Paid %.2f using Credit Card %s", amount, cc.CardNumber)
}
type PayPal struct {
Email string
}
func (pp PayPal) Pay(amount float64) string {
return fmt.Sprintf("Paid %.2f using PayPal account %s", amount, pp.Email)
}
func ProcessPayments(payments []PaymentMethod, amount float64) {
for _, p := range payments {
fmt.Println(p.Pay(amount))
}
}
func main() {
cards := []CreditCard{
{CardNumber: "1234-5678"},
{CardNumber: "8765-4321"},
}
// This is where the compiler screams at us
ProcessPayments(cards, 100.00)
}
The "Cannot Use Type" Slice Conflict
If you try to run this, Go will tell you: cannot use cards (variable of type []CreditCard) as type []PaymentMethod in argument to ProcessPayments.
It feels wrong, right? CreditCard implements PaymentMethod. Therefore, a slice of credit cards should be a slice of payment methods. But Go doesn't work that way. In Go, []CreditCard and []PaymentMethod have completely different memory layouts. A CreditCard struct is just the data for that struct; a PaymentMethod interface is actually a two-word data structure containing a pointer to the type information and a pointer to the actual data.
Go refuses to automatically "cast" the entire slice because it would have to allocate a brand new slice and wrap every single element in an interface header, which is a hidden performance cost. Go prefers to be explicit about those costs.
Converting Concrete Slices to Interface Slices
To fix this, you have to manually build the slice of interfaces. It's a bit tedious, but it makes the performance hit visible to you, the developer. I usually do it with a simple loop.
func main() {
cards := []CreditCard{
{CardNumber: "1234-5678"},
{CardNumber: "8765-4321"},
}
// We create a new slice of the interface type
paymentMethods := make([]PaymentMethod, len(cards))
for i, v := range cards {
paymentMethods[i] = v
}
ProcessPayments(paymentMethods, 100.00)
}
Implicit Satisfaction and the "Small Interface" Philosophy
The real magic of Go interfaces is that they are implicitly satisfied. Notice that CreditCard doesn't have a keyword like implements PaymentMethod. It just happens to have a Pay method with the right signature, so Go considers it a PaymentMethod. This decouples your code beautifully; you can define an interface in your package to describe what you need from a dependency, without the dependency ever knowing your interface exists.
My advice? Keep your interfaces tiny. In the Go standard library, the most powerful interfaces—like io.Reader or fmt.Stringer—often have only one single method. When you make interfaces small, they become incredibly flexible and easy to implement across different parts of your system.
Accept Interfaces, Return Structs
You'll hear this phrase a lot in the Go community. What it actually means is: don't force your functions to return an interface if they are just returning a concrete type. Return the CreditCard struct. Let the caller decide if they want to treat it as a PaymentMethod interface. This keeps your API flexible and prevents you from getting locked into a rigid hierarchy that's hard to change later.
📋 Practical Task
Build a Pluggable Notification Dispatcher
Your goal is to create a notification system that can send alerts through different channels (Email and SMS) without the main logic needing to know which channel is being used.
- Define a
Notifierinterface with a methodSend(message string) error. - Create an
EmailServicestruct with anEmailAddressfield and implement theSendmethod (just print "Sending Email to [address]: [message]"). - Create an
SMSServicestruct with aPhoneNumberfield and implement theSendmethod (just print "Sending SMS to [number]: [message]"). - Write a function called
NotifyAll(notifiers []Notifier, msg string)that loops through a slice of notifiers and callsSendon each. - In your
mainfunction, initialize one of each service, put them into a slice ofNotifier, and callNotifyAll.
There are no comments for now.