首页 > 其他 > 详细

go 接口以及对象传递

时间:2019-02-09 16:09:07      阅读:183      评论:0      收藏:0      [点我收藏+]

 

// Sample program to show how to use an interface in Go.
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 with a pointer receiver.
func (u *user) notify() {
    fmt.Printf("Sending user email to %s<%s>\n",
        u.name,
        u.email)
}

// main is the entry point for the application.
func main() {
    // Create a value of type User and send a notification.
    u := &user{"Bill", "bill@email.com"}

    sendNotification(u)

    // ./listing36.go:32: cannot use u (type user) as type
    //                     notifier in argument to sendNotification:
    //   user does not implement notifier
    //                          (notify method has pointer receiver)
}

// sendNotification accepts values that implement the notifier
// interface and sends notifications.
func sendNotification(n notifier) {
    n.notify()
}

输出

Sending user email to Bill<bill@email.com>

 

go 接口以及对象传递

原文:https://www.cnblogs.com/sea-stream/p/10357536.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!