美文网首页
Golang中Struct && Interfa

Golang中Struct && Interfa

作者: Yancey_BFD | 来源:发表于2017-01-01 15:38 被阅读358次

Struct

很多时候,我们需要自定义新的数据类型,C++里可以用class,Golang里面也同样拥有类似的定义,称之为struct。为一个struct类型,也拥有自己的方法,属性。

Method

为struct定义方法也是非常简单的,对比C++,不需要显示的将方法写在class声明里

func (Coder)GetBestAreas() string {
    ...
}

可以按如下的方法进行调用

c := Coder{name:"Li", skills:[]stirng{"C++","Golang"}}
fmt.Println(c.GetBestAreas())

Embedding

Golang里没有提供直接继承某一个struct的方法,但是却可以通过embedding字段(匿名字段)来实现。例如我们有一个Student的struct

type Human struct {
    name string
    sex string
    ...
}

还有一个用来描述程序员的struct:

type Coder struct{
    name string
    sex string
    ...
    skills []string
}

在Human和Coder里重复定义了name和sex字段,那么这时可以通过在Coder里嵌入Human类型来直接使用Human中的字段

type Coder struct {
    Human
    skills []string
}

Interface

如果说struct是一个class,那么他只能定义不含虚函数的方法,而interface确实只能定义纯虚函数,并不能含有任何字段。

type Animal interface {
    Sound() string
}

type Cat struct {
}

func (Cat) Sound() string {
    return "Miao"
}

type Dog struct {
}

func (Dog) Sound() string {
    return "Wang"
}

func main() {
    animals := []Animal{Dog{}, Cat{}}
    for _, animal := range animals {
        fmt.Println(animal.Sound())
    }
}

相关文章

网友评论

      本文标题:Golang中Struct && Interfa

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