golang 结构体札记

golang 结构体笔记

一、概念

结构体是一种聚合的数据类型,是由零个或多个任意类型的值聚合成的实体。每个值称为结构体的成员。

二、结构体声明及使用

// 声明结构体
type Employee struct {
    ID   int
    Name string
}

func main() {
    // 结构体实例化
    emp := Employee{ID: 1, Name: "Frod"}
    // 匿名字段实例化
    emp2 := Employee{1, "Frod2"}
    fmt.Println(emp)
    fmt.Println(emp2)
}

三、聚合结构

golang没有继承的概念, 推崇的是类聚合

type Address struct {
    Province string
    City     string
    Detail   string
}

type Employee struct {
    ID      int
    Name    string
    Address Address
}

func main() {
    emp := Employee{
        ID:   1,
        Name: "Frod",
        Address: Address{
            Province: "浙江省",
            City:     "杭州市",
            Detail:   "余杭区仓前镇",
        },
    }
    fmt.Println(emp)
}

四、匿名结构体

func main() {

    emp := struct {
        ID   int
        Name string
    }{
        ID:   1001,
        Name: "Frod",
    }

    fmt.Println(emp)
}

五、结构方法

type Employee struct {
    ID   int
    Name string
}

func main() {
    emp := Employee{1, "Frod"}
    fmt.Println(emp.getName())
}

func (this *Employee) getName() string {
    return this.Name
}