zoukankan      html  css  js  c++  java
  • 从接收者类型的角度来看方法集

    //从接收者类型的角度来看方法集
    Methods Receivers   Values
    (t T)           	T and *T
    (t *T)				*T
    如果使用指针接收者来实现一个接口,那么只有指向那个类型的指针才能够实现对应的接口。
    如果使用值接收者来实现一个接口,那么那个类型的值和指针都能够实现对应的接口
    // 示例
    package main
    import (
    	"fmt"
    )
    // 定义接口
    type notifier interface{
        notify()
    }
    // 定义user结构体
    type user struct{
        name string
        email string
    }
    // 使用指针接收者实现的方法
    func (u *user) notify(){
        fmt.Printf("Sending user email to %s<%s>
    ", u.name, u.email)
    }
    //sendNotification接收一个实现了notifier接口的值
    func sendNotification(n notifier){
        n.notify()
    }
    
    // 应用程序入口
    func main(){
        // 创建一个user类型的值
        u := user{"Bill", "bill@email.com"}
        //sendNotification(u)  // 这边会报错
        sendNotification(&u) // 正确写法传指针
    }
    

    -------------------------------------------

    个性签名:代码过万,键盘敲烂!!!

    如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

  • 相关阅读:
    Swift
    Swift
    Swift
    Swift
    Swift
    Swift
    Swift
    Swift
    Swift
    算法の序列
  • 原文地址:https://www.cnblogs.com/weiweivip666/p/15480656.html
Copyright © 2011-2022 走看看