发布于 2016-01-23 12:53:25 | 168 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的GO语言教程,程序狗速度看过来!

Go语言

Go是一种新的语言,一种并发的、带垃圾回收的、快速编译的语言。Go是谷歌2009年发布的第二款编程语言。2009年7月份,谷歌曾发布了Simple语言,它是用来开发Android应用的一种BASIC语言。


这篇文章主要介绍了Golang学习笔记(六):struct,本文讲解了struct的声明及初始化、struct的匿名字段(继承)、method、method继承和重写等内容,需要的朋友可以参考下

struct

struct,一组字段的集合,类似其他语言的class

放弃了大量包括继承在内的面向对象特性,只保留了组合(composition)这个最基础的特性

1.声明及初始化


type person struct {
    name string
    age  int
}

//初始化

func main() {
    var P person

    P.name = "tom"
    P.age = 25
    fmt.Println(P.name)

    P1 := person{"Tom1", 25}
    fmt.Println(P1.name)

    P2 := person{age: 24, name: "Tom"}
    fmt.Println(P2.name)
}

2.struct的匿名字段(继承)


type Human struct {
    name string
    age int
    weight int
}

tyep Student struct {
    Human //匿名字段,默认Student包含了Human的所有字段
    speciality string
}

mark := Student(Human{"mark", 25, 120}, "Computer Science")

mark.name
mark.age


能够实现字段继承,当字段名重复的时候,优先取外层的,可以通过指定struct名还决定取哪个

mark.Human = Human{"a", 55, 220}
mark.Human.age -= 1

struct不仅可以使用struct作为匿名字段,自定义类型、内置类型都可以作为匿名字段,而且可以在相应字段上做函数操作

3.method


type Rect struct {
    x, y float64
    width, height float64
}

//method


Reciver 默认以值传递,而非引用传递,还可以是指针
指针作为Receiver会对实例对象的内容发生操作,而普通类型作为Receiver仅仅是以副本作为操作对象,而不对原实例对象发生操作

func (r ReciverType) funcName(params) (results) {

}


如果一个method的receiver是*T,调用时,可以传递一个T类型的实例变量V,而不必用&V去调用这个method

func (r *Rect) Area() float64 {
    return r.width * r.height
}

func (b *Box) SetColor(c Color) {     b.color = c }

4.method继承和重写

采用组合的方式实现继承


type Human struct {
    name string
}

type Student struct {
    Human
    School string
}

func (h *Human) SayHi() {
    fmt.Println(h.name)
}

//则Student和Employee的实例可以调用
func main() {
    h := Human{name: "human"}
    fmt.Print(h.name)
    h.SayHi()

    s := Student{Human{"student"}}
    s.SayHi()

}


还可以进行方法重写

funct (e *Student) SayHi() {
    e.Human.SayHi()
    fmt.Println(e.School)
}



最新网友评论  共有(0)条评论 发布评论 返回顶部
推荐阅读
最新资讯

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务