Golang interfaces — My journey

Sachith Muhandiram
1 min readDec 31, 2019

--

I had been learning golang for around a year now. But yet, I have this fear for interfaces. I was trying my best to avoid them. But recently I had been working on my hobby project. In that I had following scenario.

My system should send three different emails for users.

  • Register to the system.
  • Login.
  • Password reset.

at my initial development, I used three different routes to handle these three scenarios. As I have fear about interfaces. Yesterday I have decide its time to use interface for this scenario and simplify the implementation.

So this is how I have implemented this scenario :

Created an interface for holding sendEmail function.

type Notifier interface {
SendEmail(user *userEmailNotification, msg string)
}

Then a struct to hold email and notification interface.

type userEmailNotification struct {
email string
emailNotification Notifier
}

And then empty struct to hold login,`register` and passwordreset.

type registerEmail struct {
}
type loginEmail struct {
}
type passwordResetEmail struct {
}

And finally SendEmail function for different scenario.

func (regiEmail registerEmail) SendEmail(user *userEmailNotification, msg string) {// this sends register email to user
}
func (loginEmail loginEmail) SendEmail(user *userEmailNotification, msg string) {
// this sends login email
}
func (passRestEmail passwordResetEmail) SendEmail(user *userEmailNotification, msg string) {// this sends password reset link
}

This is how I have used golang-interfaces for the first time for a real work.

This may be wrong or there are work around to improve this. Please suggest me them.

Wish you all a Happy and prosperous 2020 !!!

--

--

Sachith Muhandiram
Sachith Muhandiram

Written by Sachith Muhandiram

DevOps who is willing to learn and try new things.

No responses yet