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
103: Common Go Interview Questions on Interfaces
If you're heading into a Go interview, you can bet your last paycheck that you'll be grilled on interfaces. Interviewers love them because they reveal whether you actually understand how Go handles types or if you're just treating it like Java or C#. The trick is that Go interfaces are satisfied implicitly. You don't declare implements Payer; you just write the methods and the language figures it out.
Let's build a small payment processing system. This is a classic example because it perfectly demonstrates why we decouple behavior from implementation.
Defining what it means to be a Payer
First, I want to define the behavior. I don't care if the payment goes through Stripe, PayPal, or a magic hat; I just care that it can Pay an amount. I'll start by defining a small interface.
type Payer interface {
Pay(amount float64) error
}
Notice how lean that is. In a real project, I'd resist the urge to add ten other methods here. One of the most common interview questions is about "Interface Pollution." The rule of thumb is: keep your interfaces small. The smaller the interface, the more reusable it is.
Plugging in different payment gateways
Now I'll create two concrete types. I'll use pointers for the receivers because, in a real app, these structs would hold API keys or configuration that we wouldn't want to copy around on every method call.
type Stripe struct {
APIKey string
}
func (s *Stripe) Pay(amount float64) error {
fmt.Printf("Paying %.2f using Stripe (Key: %s)\n", amount, s.APIKey)
return nil
}
type PayPal struct {
Email string
}
func (p *PayPal) Pay(amount float64) error {
fmt.Printf("Paying %.2f using PayPal (Email: %s)\n", amount, p.Email)
return nil
}
At this point, both Stripe and PayPal satisfy the Payer interface. I didn't have to explicitly link them. This "duck typing" is exactly what interviewers are looking for you to explain.
The 'Nil Interface' trap I almost walked into
Here is where things get dangerous. I've seen plenty of senior devs trip over this in interviews. Let's say I write a factory function to return a Payer, but under certain conditions, it returns a nil pointer of a concrete type.
func GetPaymentMethod(method string) Payer {
if method == "stripe" {
return &Stripe{APIKey: "sk_test_123"}
}
// I'm returning a nil pointer to a Stripe struct
var s *Stripe = nil
return s
}
Now, look at what happens if I check for nil in my main logic:
payment := GetPaymentMethod("unknown")
if payment == nil {
fmt.Println("Payment method is nil!")
} else {
fmt.Println("Payment method is NOT nil!")
}
You'd expect it to print "Payment method is nil!", right? Wrong. It prints "Payment method is NOT nil!".
I remember the first time I hit this; I spent an hour debugging. Here is the "interview answer": An interface in Go is actually a tuple of (value, type). For an interface to be truly nil, both the value and the type must be nil. In my code above, the interface's type was set to *Stripe, but the value was nil. Since the type is present, the interface itself is not nil.
To fix this, I should always return the literal nil instead of a typed nil pointer when I want to indicate the absence of a value.
Handling dynamic data with any
Finally, interviewers will ask about interface{} (or any in Go 1.18+). They want to know how you get your actual data back out of that "black box." The answer is type assertions or type switches.
Let's say we want to log some metadata about the payment, but the metadata format varies between providers.
func LogMetadata(data any) {
switch v := data.(type) {
case string:
fmt.Printf("Logging string metadata: %s\n", v)
case int:
fmt.Printf("Logging numeric ID: %d\n", v)
case map[string]string:
fmt.Printf("Logging map metadata: %v\n", v)
default:
fmt.Println("Unknown metadata format")
}
}
Using a type switch is the idiomatic way to handle any. It's cleaner than doing a chain of if v, ok := data.(string); ok { ... } assertions.
📋 Practical Task
Build a Multi-Provider Notification Dispatcher
To put these concepts into practice, you are going to build a notification system that can send alerts via different channels (Email and SMS), while avoiding the "nil interface" trap.
Your requirements:
- Define a
Notifierinterface with aSend(message string) errormethod. - Implement the
Notifierinterface for two structs:EmailServiceandSMSService. - Write a factory function
NewNotifier(channel string) Notifier.- If the channel is "email", return an
EmailService. - If the channel is "sms", return an
SMSService. - If the channel is unknown, return a literal
nil(do not return a typed nil pointer).
- If the channel is "email", return an
- In your
mainfunction:- Call
NewNotifierwith an invalid channel. - Verify that the resulting interface is actually
nilusing anifstatement. - Create a slice of
Notifiercontaining both an email and SMS service, and loop through them to send a "System Alert" message.
- Call
There are no comments for now.