• Go嵌入类型


    package main
    
    import "fmt"
    
    //notifier是一个定义了 通知类行为的接口
    type notifier interface {
    	notify()
    }
    //user 在程序里定义一个用户类型
    type user struct {
    	name string
    	email string
    }
    
    //通过user类型的指针调用的方法
    func (u *user) notify()  {
    	fmt.Printf("Sending user email to %s<%s>
    ",
    		u.name,
    		u.email)
    }
    //admin是一个拥有权限的管理员用户
    type admin struct {
    	user
    	level string
    }
    
    func sendNotification(n notifier)  {
    	n.notify()
    }
    func main() {
    	ad:=admin{
    		user:user{
    			name:"john smith",
    			email: "john@yahoo.com",
    		},
    		level: "super",
    	}
    	sendNotification(&ad)
    }
    
    

    这里ad是admin的实例对象,上面我们没有用admin类型实现这个接口,但是因为用了内嵌的user的指针类型实现过,所以得知内部类型实现的接口自动提升到外部类型
    如果外部类型并不需要使用内部类型的实现,就下面这样用

    package main
    
    import "fmt"
    
    //notifier是一个定义了 通知类行为的接口
    type notifier interface {
    	notify()
    }
    //user 在程序里定义一个用户类型
    type user struct {
    	name string
    	email string
    }
    
    //通过user类型的指针调用的方法
    func (u *user) notify()  {
    	fmt.Printf("Sending user email to %s<%s>
    ",
    		u.name,
    		u.email)
    }
    //admin是一个拥有权限的管理员用户
    type admin struct {
    	user
    	level string
    }
    
    //admin类型值的指针,调用的方法
    func (a *admin) notify(){
    	fmt.Printf("Sending admin email to %s<%s>
    ",
    		a.name,
    		a.email)
    
    }
    
    func sendNotification(n notifier)  {
    	n.notify()
    }
    func main() {
    	ad:=admin{
    		user:user{
    			name:"john smith",
    			email: "john@yahoo.com",
    		},
    		level: "super",
    	}
    	sendNotification(&ad)
    	//访问内部类型的方法
    	ad.user.notify()
    
    	//外部类型的方法没有被提升
    	ad.notify()
    }
    
    
    
    
    

    添加一个由admin指针类型的接收者实现的notify方法,这样后面再使用ad的时候外部类型就不会再提升了

    来源:Go in Action

  • 相关阅读:
    mysql查看所有触发器以及存储过程等操作集合【转】
    Hutool之Http工具类使用
    SpringCloud之Sentinel
    SpringCloud之Gateway
    com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
    [AWS DA Guru] SQS
    [AWS DA Guru] Kinesis
    [AWS DA Guru] SNS & SES
    [Typescript] Prevent Type Widening of Object Literals with TypeScript's const Assertions
    [AWS] Updating Elastic Beans Talks & RDS
  • 原文地址:https://www.cnblogs.com/c-x-a/p/14062738.html
Copyright © 2020-2023  润新知