目录

struct


struct

Go 中的结构也是一种数据结构,它可包含零个或多个任意类型的字段,并将它们表示为单个实体。

1 声明和初始化结构

type Employee struct {
    ID        int
    FirstName string
    LastName  string
    Address   string
}
var john Employee
employee := Employee{1001, "John", "Doe", "Doe's Street"}
employee := Employee{LastName: "Doe", FirstName: "John"}
employee.ID = 1001
fmt.Println(employee.FirstName)

可使用 & 运算符生成指向结构的指针

    employeeCopy := &employee
    employeeCopy.FirstName = "David"

2 结构嵌入

type Employee struct {
    Information Person
    ManagerID   int
}
type Person struct {
    ID        int
    FirstName string
    LastName  string
    Address   string
}
var employee Employee
employee.Information.FirstName = "John"

展开嵌入

type Employee struct {
    Person
    ManagerID int
}
type Person struct {
    ID        int
    FirstName string
    LastName  string
    Address   string
}
    employee := Employee{
        Person: Person{
            FirstName: "John",
        },
    }
    employee.LastName = "Doe"
    fmt.Println(employee.FirstName)

3 用 JSON 编码和解码结构

Go 对 JSON 格式提供很好的支持,该格式已包含在标准库包中

若要将结构编码为 JSON,请使用 json.Marshal 函数。 若要将 JSON 字符串解码为数据结构,请使用 json.Unmarshal 函数

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    ID        int
    FirstName string `json:"name"`
    LastName  string
    Address   string `json:"address,omitempty"`
}

type Employee struct {
    Person
    ManagerID int
}

type Contractor struct {
    Person
    CompanyID int
}

func main() {
    employees := []Employee{
        Employee{
            Person: Person{
                LastName: "Doe", FirstName: "John",
            },
        },
        Employee{
            Person: Person{
                LastName: "Campbell", FirstName: "David",
            },
        },
    }

    data, _ := json.Marshal(employees)
    fmt.Printf("%s\n", data)

    var decoded []Employee
    json.Unmarshal(data, &decoded)
    fmt.Printf("%v", decoded)
}