美文网首页
Golang learning 结构体 struct 与面向对

Golang learning 结构体 struct 与面向对

作者: wangyongyue | 来源:发表于2019-05-14 15:59 被阅读0次

Go 语言并不是传统意义上的面向对象语言,但是实现很小的面向对象的机制。
匿名嵌入并不是继承,无法实现多态处理,虽然配合方法集,可用接口来实现一些类似操作,但是其本质是完全不同的。

type Animal struct {          声明Animal
    name string
    age  int
}
type Cat struct {

    Animal                       匿名字段
    teeth string  "牙"         "牙" 不是注释,字段标签(tag)不是注释,是用来描述字段的元数据,是struct的一部分
    leg  int
}
type Animal struct {                        声明Animal类
    name string
    age  int
}
type AnimalAction interface {        声明AnimalAction  接口类

    eat()                                        声明func
    voice()                                     声明func

}
func (a Animal) eat(){                  Animal实现接口AnimalAction    方法eat()

    fmt.Print("eat")
}
func (a Animal) voice(){                 Animal实现接口AnimalAction    方法voice()

    fmt.Print("voice")
}




type Cat struct {                         声明Cat类  
    Animal                                匿名字段Animal     嵌入类型
    teeth string "牙"
    leg  int
}

type NewAction interface {     声明NewAction  接口类
    run()
        sing(s func(name string))   声明闭包sing
}

func (c Cat) eat(){                    Cat实现 func eat(),类似继承的重写,但不是重写。 
    c.Animal.eat()                    Cat调用Animal func eat(),类似super.eat()  但不是调用父类方法
    fmt.Print("cat eat")

}
func (c Cat) run(){                    Cat实现NewAction func run()

    fmt.Print("cat run")

}
func (c Cat) sing(s func(name string)){       实现闭包sing
    s("cat")
}

func test(){


   a := Animal{
    "a",
    12,

   }
   a.eat()
   a.voice()

   c := Cat{
    Animal{
        "cat",
        1,
    },
    "尖牙",
    4,
   }

   c.eat()
   c.voice()
   c.run()

   c.sing(func(name string) {         调用闭包

      fmt.Print("\n" + name + "sing")
   })


}

相关文章

  • Golang learning 结构体 struct 与面向对

    Go 语言并不是传统意义上的面向对象语言,但是实现很小的面向对象的机制。匿名嵌入并不是继承,无法实现多态处理,虽然...

  • golang类和结构体

    golang结构体和类 golang中并没有明确的面向对象的说法,实在要扯上的话,可以将struct比作其它语言中...

  • 15 Golang结构体详解(一)

    Golang中没有“类”的概念,Golang中的结构体struct和其他语言中的类有点相似。和其他面向对象语言中的...

  • Golang——结构体struct

    Go语言中没有“类”的改变,不支持类的“继承”等面向对象概念。Go语言中通过结构体的内嵌再配合接口比面向对象更具有...

  • iOS(swift)类和结构体的区别

    类是面向对象编程;结构体是面向协议编程(面向对象的升级)。swift推荐在app中使用结构体(struct),类(...

  • Golang struct

    Golang struct 一个结构体(struct)就是一个字段的集合 type Vertex str...

  • Golang笔记: 结构体(struct)

    结构体定义 go语言的关键字 type 可以将各种基本类型定义为自定义类型,包括整型、字符串、布尔等。结构体是一种...

  • Golang 入门 : 结构体(struct)

    Go 通过类型别名(alias types)和结构体的形式支持用户自定义类型,或者叫定制类型。试图表示一个现实世界...

  • GeekBand Swift高级编程(第二周)

    结构与枚举 认识结构(struct)struct属于值类型,具有拷贝语义(赋值和传参)struct不支持面向对象,...

  • 结构 struct golang

    原文链接:结构struct-GOLANG

网友评论

      本文标题:Golang learning 结构体 struct 与面向对

      本文链接:https://www.haomeiwen.com/subject/erjsaqtx.html