go接口及嵌入类型例子

书上看的。慢慢领会。。

package main

import (
	"fmt"
)

type notifier interface {
	notify()
}

type user struct {
	name  string
	email string
}

func (u *user) notify() {
	fmt.Printf("Sending user email to %s<%s>\n",
		u.name,
		u.email)
}

type admin struct {
	user
	level string
}

func (a *admin) nofity() {
	fmt.Printf("Sending admin email to %s<%s>\n",
		a.name,
		a.email,
		a.level)
}

func main() {
	ur := user{
		name:  "Bill smith",
		email: "Bill@email.com",
	}

	ad := admin{
		user: user{
			name:  "John smith",
			email: "John@email.com",
		},
		level: "super",
	}

	sendNotification(&ur)
	sendNotification(&ad)

	ad.user.notify()
	ad.nofity()

}

func sendNotification(n notifier) {
	n.notify()
}

  go接口及嵌入类型例子

上一篇:C语言及程序设计进阶例程-10 预处理之条件编译


下一篇:设计模式—装饰模式的C++实现