Golang interface method with parameter

Golang interface method with parameter

Golang’s interface concept encapsulates behavior, allowing types to fulfill certain expectations. The straightforward nature of interfaces contributes to clean, modular, and maintainable code.

This blog post delves into the pragmatic use of “Golang interface method with parameter,” elucidating how this feature enhances code flexibility and extensibility.

Defining an Interface Method with Parameters

In Golang, an interface can declare methods that accept parameters. This characteristic enables interfaces to model diverse behaviors without sacrificing simplicity. Let’s illustrate this with a practical example.

package main

import "fmt"

type Messenger interface {
    SendMessage(message string)

type EmailMessenger struct {
    EmailAddress string

func (e *EmailMessenger) SendMessage(message string) {
    fmt.Printf("Sending email to %s: %s\n", e.EmailAddress, message)

type SMSMessenger struct {
    PhoneNumber string

func (s *SMSMessenger) SendMessage(message string) {
    fmt.Printf("Sending SMS to %s: %s\n", s.PhoneNumber, message)

func main() {
    emailMessenger := &EmailMessenger{EmailAddress: "john@example.com"}
    smsMessenger := &SMSMessenger{PhoneNumber: "+123456789"}

    sendNotification(emailMessenger, "Hello via Email")
    sendNotification(smsMessenger, "Hi via SMS")

func sendNotification(messenger Messenger, message string) {

Real-world Application: Extensible Notifications

Imagine a scenario where a notification system needs to support various delivery channels. By defining the SendMessage method with a parameter in the Messenger interface, concrete types like EmailMessenger and SMSMessenger can implement their unique messaging logic.

Code Flexibility and Interchangeability

The sendNotification function exemplifies the power of Golang interfaces. By accepting the Messenger interface as a parameter, it accommodates different types implementing the interface, showcasing how Golang’s design promotes code flexibility and interchangeability.

Final Thought

In conclusion, the ability to define interface methods with parameters in Golang is a fundamental feature that contributes to the language’s simplicity and versatility. Embracing this approach facilitates the creation of modular, extensible, and seamlessly integrated systems, showcasing the elegance of Golang’s design philosophy.

You May Also Like: