Go结构体嵌套

1. Go结构体嵌套

1.1 嵌套别的结构体

package main

import (
    "encoding/json"
    "fmt"
)
type addr struct {
    Province string
    City string
}
type info struct {
    Age int
    Email string
}
type student struct {
    Name string
    Address addr   // 嵌套别的结构体
}

func main() {
    
    st := student{
        Name: "网五",
        Address: addr{
            Province: "bj",
            City:     "bj",
        }
    }
    s1,_  := json.Marshal(st)
    fmt.Println(st)
    fmt.Println(string(s1))
}

结果

{网五 {bj bj} { } {0 }}
{"Name":"网五","Address":{"Province":"bj","City":"bj"},"Province":"","City":"","Age":0,"Email":""}

1.2 匿名嵌套别的结构体,类型名做名称

package main

import (
    "encoding/json"
    "fmt"
)

type addr struct {
    Province string
    City string
}
type info struct {
    Age int
    Email string
}
type student struct {
    Name string
    Address addr   // 嵌套别的结构体
    addr // 匿名嵌套别的结构体,就使用类型名做名称
    info
}

func main() {

    st := student{
        Name: "网五",
        Address: addr{
            Province: "bj",
            City:     "bj",
        },
        addr:addr{"bj", "bj"},   // 属性名称和结构体名称保持一致
        info:info{19,"aaa@navinfoolpm"},
    }
    s1,_  := json.Marshal(st)
    fmt.Println(st)
    fmt.Println(string(s1))
}

结果

{网五 {bj bj} {bj bj} {19 aaa@navinfoolpm}}
{"Name":"网五","Address":{"Province":"bj","City":"bj"},"Province":"bj","City":"bj","Age":19,"Email":"aaa@navinfoolpm"}
原文地址:https://www.cnblogs.com/supery007/p/13328347.html