Go语言的接口interface、struct和组合、继承

原创
2021/06/05 11:46
阅读数 643

Go语言的接口interface、struct和组合、继承

interface相当与c++ 基类,interface实现多态功能
同时也支持组合

继承实现:
  1 package main
  2 
  3 import(
  4         "fmt"
  5 )
  6 
  7 type base interface { //类似基类定义
  8     virtualfunc() int //类似虚函数抽象定义
  9 }
 10 
 11 
 12 type der1 int //类似派生类1定义
 13 
 14 func (der1) virtualfunc() int { //类似派生类1虚函数具体实现
 15     fmt.Printf("I'm der1\n")
 16     return 1
 17 }
 18 
 19 type der2 struct { //类似派生类2定义
 20     //nothing
 21 }
 22 
 23 func (der2) virtualfunc() int { //类似派生类2虚函数具体实现
 24     fmt.Printf("I'm der2\n")
 25     return 2
 26 }
 27 
 28 func somefunc(b base) { //作为某个函数的形参
 29     b.virtualfunc()
 30 }
 31 
 32 func main() {
 33         //base对象
 34     var baseobj base
 35 
 36         //child1对象
 37     var d1 der1
 38     baseobj = d1
 39     somefunc(baseobj)
 40 
 41         //child2对象
 42     var d2 der2
 43     baseobj = d2
 44     somefunc(baseobj)
 45 }

组合实现:
  1 package main
  2 
  3 import (
  4     "fmt"
  5 )
  6 
  7 type Base struct {
  8     // nothing
  9 }
 10 
 11 func (b *Base) ShowA() {
 12     fmt.Println("showA")
 13     b.ShowB()
 14 }
 15 
 16 func (b *Base) ShowB() {
 17     fmt.Println("showB")
 18 }
 19 
 20 
 21 type Derived struct {
 22     Base//组合Base
 23 }
 24 
 25 
 26 func (d *Derived) ShowB() {
 27     fmt.Println("Derived showB")
 28 }
 29 
 30 
 31 func main() {
 32         //对象创建
 33     d := Derived{}
 34     d.ShowA()
 35 }

type name 和type struct区别
type不支持隐式转换/函数共用

  1 package main
  2 
  3 import (
  4     "fmt"
  5 )
  6 
  7 type Mutex struct {
  8     // nothing
  9 }
 10 
 11 func (m *Mutex) Lock() {
 12     fmt.Println("mutex Lock")
 13 }
 14 
 15 func (m *Mutex) lck() {
 16    fmt.Println("mutex lock")
 17 }
 18 
 19 func (m *Mutex) Unlock() {
 20     fmt.Println("mutex unlock")
 21 }
 22 
 23 type newMutex Mutex
 24 
 25 type structMutex struct {
 26     Mutex
 27 }
 28 
 29 
 30 func main() {
 31         //内部方法
 32     m1 := Mutex{}
 33     m1.Lock()
 34     m1.lock()
 35 
 36     //n1 := newMutex{}
 37     //n1.Lock()     //没有Lock()方法
 38 
 39         //组合
 40     x1 := structMutex{}
 41     x1.Lock()
 42 
 43 }

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部