Last active
February 26, 2020 20:34
-
-
Save stnc/239bcf543a578e3fdb97e07321a3df76 to your computer and use it in GitHub Desktop.
A Real-World Example of Go Interfaces
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// author Dirk Hoekstra | |
//link https://medium.com/better-programming/a-real-world-example-of-go-interfaces-98e89b2ddb67 | |
import "fmt" | |
type User1 struct { | |
Name string | |
Email string | |
} | |
type UserNotifier1 interface { | |
SendMessage(user *User1, message string) error | |
} | |
type EmailNotifier1 struct { | |
} | |
func (notifier EmailNotifier1) SendMessage(user *User1, message string) error { | |
_, err := fmt.Printf("Sending email to %s with content %s\n", user.Name, message) | |
return err | |
} | |
func main() { | |
user := User1{"Dirk", "[email protected]"} | |
fmt.Printf("Welcome %s\n", user.Name) | |
var userNotifier UserNotifier1 | |
userNotifier = EmailNotifier1{} | |
userNotifier.SendMessage(&user, "Interfaces all the way!") | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// author Dirk Hoekstra | |
//link https://medium.com/better-programming/a-real-world-example-of-go-interfaces-98e89b2ddb67 | |
import "fmt" | |
type User struct { | |
Name string | |
Email string | |
Notifier UserNotifier | |
} | |
type UserNotifier interface { | |
SendMessage(user *User, message string) error | |
} | |
type EmailNotifier struct { | |
} | |
type SmsNotifier struct { | |
} | |
func (notifier SmsNotifier) SendMessage(user *User, message string) error { | |
_, err := fmt.Printf("Sending SMS to %s with content %s\n", user.Name, message) | |
return err | |
} | |
func (notifier EmailNotifier) SendMessage(user *User, message string) error { | |
_, err := fmt.Printf("Sending email to %s with content %s\n", user.Name, message) | |
return err | |
} | |
func (user *User) notify(message string) error { | |
return user.Notifier.SendMessage(user, message) | |
} | |
func main() { | |
user1 := User{"Dirk", "[email protected]", EmailNotifier{}} | |
user2 := User{"Justin", "[email protected]", SmsNotifier{}} | |
user1.notify("Welcome Email user!") | |
user2.notify("Welcome SMS user!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment