forked from hoanhan101/ultimate-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
embedding_4.go
65 lines (53 loc) · 1.66 KB
/
embedding_4.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// ---------------------------------------------
// OUTER AND INNER TYPE IMPLEMENTING THE SAME INTERFACE
// ---------------------------------------------
package main
import "fmt"
// notifier is an interface that defined notification type behavior.
type notifier interface {
notify()
}
// user defines a user in the program.
type user struct {
name string
email string
}
// notify implements a method notifies users of different events.
func (u *user) notify() {
fmt.Printf("Sending user email To %s<%s>\n", u.name, u.email)
}
// admin represents an admin user with privileges.
type admin struct {
user
level string
}
// notify implements a method notifies admins of different events.
// We now have two different implementations of notifier interface, one for the inner type,
// one for the outer type. Because the outer type now implements that interface, the inner type
// promotion doesn't happen. We have overwritten through the outer type anything that inner type
// provides to us.
func (a *admin) notify() {
fmt.Printf("Sending admin email To %s<%s>\n", a.name, a.email)
}
func main() {
// Create an admin user.
ad := admin{
user: user{
name: "Hoanh An",
email: "[email protected]",
},
level: "superuser",
}
// Send the admin user a notification.
// The embedded inner type's implementation of the interface is NOT "promoted"
// to the outer type.
sendNotification(&ad)
// We can access the inner type's method directly.
ad.user.notify()
// The inner type's method is NOT promoted.
ad.notify()
}
// sendNotification accepts values that implement the notifier interface and sends notifications.
func sendNotification(n notifier) {
n.notify()
}