Skip to Content
Course content

103: Common Go Interview Questions on Interfaces

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 Notifier interface with a Send(message string) error method.
  • Implement the Notifier interface for two structs: EmailService and SMSService.
  • 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).
  • In your main function:
    • Call NewNotifier with an invalid channel.
    • Verify that the resulting interface is actually nil using an if statement.
    • Create a slice of Notifier containing both an email and SMS service, and loop through them to send a "System Alert" message.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.