Golang继承,指针与非指针的区别

package main

import "fmt"
import "time"

type cc interface{
   MyPrint()
   MyPrint2()
}

type cc1 struct{
   a int
}
type cc2 struct{
   *cc1
}
type cc3 struct{
   cc1
}

func(c *cc1)MyPrint(){
   fmt.Println("cc1 myprint.")
}

func(c cc1)MyPrint2(){
   fmt.Println("--------cc1 myprint2.")
}

func(c *cc2)MyPrint(){
   fmt.Println("cc2 myprint.")
}

func(c *cc3)MyPrint(){
   fmt.Println("cc3 myprint.")
}


func main(){
   defer func() {
      if err := recover(); err != nil{
         fmt.Println("recover err:", err)
         duration := time.Duration(10)*time.Second
         time.Sleep(duration)
      }
   }()

   c := &cc1{}
   c.MyPrint()
   (*c).MyPrint()

   c2 := &cc2{}
   c2.MyPrint()
   (*c2).MyPrint()
   c22 := cc2{}
   c22.MyPrint()
   //c2.MyPrint2() //error
   //(*c2).MyPrint2() //error
   //c22.MyPrint2() //error
   c222 := &cc2{&cc1{}}
   c222 .MyPrint2() // ok,上面报error,是因为指针未初始化...无语
    

   c3 := &cc3{}
   c3.MyPrint()
   (*c3).MyPrint()
   c33 := cc3{}
   c33.MyPrint()
   c3.MyPrint2()
   (*c3).MyPrint2()
   c33.MyPrint2()

   duration := time.Duration(300)*time.Second
   time.Sleep(duration)
}

对比1:对比

对比2:Go值接收者方法和指针接收者方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值