Skip to Content
Course content

237: Interface Satisfaction Implicitly

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

I remember when I first switched to Go from Java. I spent a good twenty minutes staring at a piece of code, wondering why the developer had forgotten to declare that a class implemented an interface. I kept looking for the implements keyword, but it just wasn't there. That's when I realized Go does things differently.

Setting up a simple Sender

Let's play this out. I want to build a small notification system. I've got different ways to send messages—email, SMS, maybe Slack—but the rest of my app shouldn't care how the message is sent, just that it can be sent. So, I'll start by defining an interface.

type Sender interface {
    Send(message string) error
}

Now, I'll create a concrete type for sending emails. I'll give it a from address so it's a bit more realistic.

type EmailSender struct {
    FromAddress string
}

func (e EmailSender) Send(msg string) error {
    fmt.Printf("Sending email from %s: %s\n", e.FromAddress, msg)
    return nil
}

At this point, if you're coming from an OOP background, you're probably waiting for me to write type EmailSender implements Sender. But I'm not going to. I'm just going to try and use it in a function that requires a Sender and see if the compiler yells at me.

Wait, where is the 'implements' keyword?

Let's write a function that takes the interface and call it with our EmailSender.

func NotifyUser(s Sender, msg string) {
    err := s.Send(msg)
    if err != nil {
        fmt.Println("Error sending notification:", err)
    }
}

func main() {
    email := EmailSender{FromAddress: "bot@company.com"}
    NotifyUser(email, "Your order has shipped!")
}

I'll run this. And... it works. No compiler errors, no warnings. The EmailSender was accepted as a Sender simply because it possessed the Send method with the correct signature.

This is what we call implicit satisfaction. In Go, you don't explicitly announce that a type satisfies an interface. If the type has the required methods, it satisfies the interface. Period. I actually love this because it decouples the definition of the interface from the implementation. I could define an interface in my own package to describe behavior from a third-party library that I don't even have the source code for.

Testing the boundaries

But what happens if I mess up? Let's see if the compiler is actually checking this or if I've stumbled into some strange Go magic. I'll create another sender, but I'll give the method a slightly different name.

type SMSSender struct {
    PhoneNumber string
}

func (s SMSSender) Dispatch(msg string) error {
    fmt.Printf("Sending SMS to %s: %s\n", s.PhoneNumber, msg)
    return nil
}

I called it Dispatch instead of Send. Now, let's try to pass an SMSSender into NotifyUser:

sms := SMSSender{PhoneNumber: "555-0199"}
NotifyUser(sms, "Your code is 1234")

The compiler catches it immediately. It tells me that SMSSender does not implement Sender because the Send method is missing. This proves that the check is rigorous; it's just invisible. You don't have to maintain a giant list of implements clauses at the top of your structs. You just write the methods, and the types "fit" where they are needed.




📋 Practical Task

Building a Pluggable Data Archiver

You are building a system that needs to archive different types of data to different destinations (e.g., a Local Disk, a Cloud Bucket). You need to ensure that any archiver used by the system satisfies a specific interface without explicitly declaring it.

Your Task:

  • Define an interface named Archiver that requires a method Archive(data []byte) error.
  • Create a struct named DiskArchiver with a field FilePath string.
  • Implement the Archive method for DiskArchiver (it can just print "Saving to [FilePath]").
  • Create a struct named CloudArchiver with a field BucketName string.
  • Implement the Archive method for CloudArchiver (it can just print "Uploading to [BucketName]").
  • Write a function called PerformBackup that takes an Archiver and a slice of bytes, then calls the Archive method.
  • In your main function, instantiate both archivers and pass them into PerformBackup to demonstrate implicit satisfaction.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.