/
struct_embedding.go
48 lines (42 loc) · 1.01 KB
/
struct_embedding.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
package main
import "fmt"
type Notifier interface {
notify()
}
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
// Struct Not Embedding
type Channel struct {
Owner User
ChannelName string
}
// Struct Embedding, Inner type promotion
type Merchant struct {
User
ShopName string
}
func (u *User) notify() {
fmt.Printf("Type: %T, Sending user email To %s<%s>\n", u, u.Name, u.Email)
}
// --------------------
// Polymorphic function
// --------------------
func sendNotification(n Notifier) {
n.notify()
}
func main() {
// Struct method, call method direct
user := User{Name: "n", Email: "e"}
user.notify()
sendNotification(&user)
// Struct Not Embedding, call method through the field owner
channel := &Channel{Owner: user, ChannelName: "c"}
channel.Owner.notify()
sendNotification(&channel.Owner)
// Struct Embedding, Inner type promotion, call method directly
merchant := &Merchant{User: User{Name: "n", Email: "e"}, ShopName: "s"}
merchant.notify()
sendNotification(merchant)
}