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"}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM