天天看點

【go語言 基礎系列】結構體及JSON編碼

【結構體】

首字面大寫,可導出的

結構體的零值由其成員的零值組成

空結構體,沒有任何成員  struct{}

【指派】

方法1:通過字面量指派

type Point struct{
	x int
	y int
}

p:=Point{1,2}
           

方法2:通過指定全部或者部分成員變量的名稱和值來初始化結構體變量

p:=Point{x=1}
           

另外,大型的結構體 通過結構體指針的方式傳遞資料

pp:=&Point{1,2}

【結構體的比較】

如果結構體的所有成員都是可以比較的,那麼該結構體就是可以比較的。如果字段順序不同,則是不同的類型

package main

import (
        "fmt"
)

type addr1 struct {
        ip   string
        port int
}

type addr2 struct {
        port int
        ip   string
}

func main() {
        a1 := addr1{ip: "127.0.0.1", port: 8080}
        a2 := addr2{ip: "127.0.0.1", port: 8080}
        fmt.Println(a1.ip == a2.ip && a1.port == a2.port)
      //  fmt.Println(a1 == a2)
}
           

去掉注釋後 會有如下錯誤:./a.go:21:17: invalid operation: a1 == a2 (mismatched types addr1 and addr2)

【JSON】

JSON最基本的類型是數字、布爾值及字元串。字元串使用雙引号,使用反斜杠做為轉移字元

隻有可導出的字段才能轉義為JSON字段,及GO中的struct成員變量首字面大寫

【結構體編碼JSON】

通過以下兩個函數可實作

func Marshal(v interface{}) ([]byte, error) {}
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error){}
           

例子如下

package main

import (
        "encoding/json"
        "fmt"
        "log"
)

type Movie struct {
        Title  string
        Year   int  `json:"released"`  //在json中通過released替換Year字段
        Color  bool `json:"color,omitempty"` //omitempty 成員的值是零值或者為空,則不輸出到JSON中
        Actors []string
}

func main() {
        m := []Movie{
                {Title: "aa", Year: 2000, Color: false,
                        Actors: []string{"HB", "IB"}},
                {Title: "bb", Year: 2001, Color: true,
                        Actors: []string{"PN"}},
                {Title: "cc", Year: 2002,
                        Actors: []string{"as", "sd", "sd"}}}
        data, err := json.Marshal(m)
        if err != nil {
                log.Fatalf("JSON marshaling failed:%s\n", err)
        }
        fmt.Printf("%s\n", data)
        fmt.Println("##")

        data2, err := json.MarshalIndent(m, "%", "@")
        if err != nil {
                log.Fatalf("JSON marshaling fialed:%s\n", err)
        }
        fmt.Printf("%s\n", data2)
}
           

輸出結果如下

[{"Title":"aa","released":2000,"Actors":["HB","IB"]},{"Title":"bb","released":2001,"color":true,"Actors":["PN"]},{"Title":"cc","released":2002,"Actors":["as","sd","sd"]}]

##

[

%@{

%@@"Title": "aa",

%@@"released": 2000,

%@@"Actors": [

%@@@"HB",

%@@@"IB"

%@@]

%@},

%@{

%@@"Title": "bb",

%@@"released": 2001,

%@@"color": true,

%@@"Actors": [

%@@@"PN"

%@@]

%@},

%@{

%@@"Title": "cc",

%@@"released": 2002,

%@@"Actors": [

%@@@"as",

%@@@"sd",

%@@@"sd"

%@@]

%@}

%]

MarshalIndent(v interface{}, prefix, indent string) 函數中,prefix 為字首,本例中的“%”, indent為縮進,本例中的“@”