Go 結構體使用注意事項和細節

2021-10-07 16:40:35 字數 2439 閱讀 2413

//結構體

type point struct

//結構體

type rect struct

func main() , point}

//r1有四個int, 在記憶體中是連續分布

//列印位址

fmt.printf("r1.leftup.x 位址=%p r1.leftup.y 位址=%p r1.rightdown.x 位址=%p r1.rightdown.y 位址=%p \n",

&r1.leftup.x, &r1.leftup.y, &r1.rightdown.x, &r1.rightdown.y)

}

r1.leftup.x 位址=0xc00009e120 r1.leftup.y 位址=0xc00009e128 r1.rightdown.x 位址=0xc00009e130 r1.rightdown.y 位址=0xc00009e138

//結構體

type point struct

//結構體

type rect2 struct

func main() , &point0}

//列印位址

fmt.printf("r2.leftup 本身位址=%p r2.rightdown 本身位址=%p \n",

&r2.leftup, &r2.rightdown)

//他們指向的位址不一定是連續..., 這個要看系統在執行時是如何分配

fmt.printf("r2.leftup 指向位址=%p r2.rightdown 指向位址=%p \n",

r2.leftup, r2.rightdown)

}

r2.leftup 本身位址=0xc0000881e0 r2.rightdown 本身位址=0xc0000881e8

r2.leftup 指向位址=0xc0000a0080 r2.rightdown 指向位址=0xc0000a0090

import "encoding/json"json包實現了json物件的編譯碼。json物件和go型別的對映關係請參見marshal和unmarshal函式的文件。

func marshal(v inte***ce{}) (byte, error)
- 欄位的標籤是"-"

- 欄位是空值,而其標籤指定了omitempty選項

// 欄位被本包忽略

field int `json:"-"`

// 欄位在json裡的鍵為"myname"

field int `json:"myname"`

// 欄位在json裡的鍵為"myname"且如果欄位為空值將在物件中省略掉

field int `json:"myname,omitempty"`

// 欄位在json裡的鍵為"field"(預設值),但如果欄位為空值會跳過;注意前導的逗號

field int `json:",omitempty"`

int64string int64 `json:",string"`
type monster struct

func main()

// 將monster變數序列化為 json格式字串

// json.marshal 函式中使用反射

golang結構體注意事項和使用細節

package main import encoding json fmt type point struct type rect struct type rect2 struct type monster struct func main point fmt.println r1 fmt.prin...

結構體注意事項

include struct stu char name int main void struct stu student struct stu student1 strcpy student1 name,zhangsan 編譯能通過但會出現斷錯誤。strcpy student name,zhang...

go 函式使用時的注意事項和細節

函式的心餐列表可以時多個,返回值列表也可以是多個 形參列表和返回值列表的資料型別可以是值型別和引用型別 函式的命名遵循識別符號命名規範,首字母不能是數字,首字母大寫該函式可以被本包檔案和其他包檔案使用,首字母小寫,將只能被本包檔案使用,其他包檔案不能使用 函式中的變數是區域性的,函式外不生效 基本資...