A-Real-World-Example-of-Go-Interfaces
孤独的孩子,悄悄在风中长大了。
Suppose I’m building a web app in Go. In my app, I want to send a message to my users. I can send a message to the users via email or SMS. This would be a perfect use case for interfaces.
For this hypothetical web app, I create the following main.go
file.
1 | package main |
The User struct represents a user.
You can see I created a UserNotifier of type interface that has a single function: SendMessage()
.
To implement this interface, I have to create a struct that implements the SendMessage()
function.
1 | type EmailNotifier struct { |
As you can see, I created a new EmailNotifier struct. Then I implemented the SendMessage() method on the struct. Note that in this example, the EmailNotifier simply prints a message. In the real world, you would probably call an email API such as Mailgun.
And that’s it, the interface is now implemented.
The next thing to do is send an email to the user using the UserNotifier interface.
1 | func main() { |
When running this program, the SendMessage() of the EmailNotifier is called correctly.
1 | go build -o main main.go |
Let’s implement an SMS interface as well.
1 | type SmsNotifier struct { |
One cool feature is we can store the notifier in the user struct. In this way, each user will have a personal notifier.
1 | type User struct { |
You can then add a handy method to the User struct that notifies the user using the UserNotifier interface.
1 | func (user *User) notify(message string) error { |
Finally, I created two users in the main() function and called the notify() method.
1 | func main() { |
The final result worked as expected.
1 | go build -o main main.go |
https://medium.com/better-programming/a-real-world-example-of-go-interfaces-98e89b2ddb67