struct

類似於js object。

type Account struct {
    id      int
    name    int
}

必須大寫

上面範例在 json marshal 後無法解析

原因為 屬性第一個字必須大寫,struct名字第一個字也要大寫。

type Account struct {
    Id      int
    Name    int
}

初始化

如果只有一個欄位最後要加逗點

point := struct{ x, y int }{10, 20}
或是
point := new(Account)

更改值

傳值

傳地址

如果是傳遞指,則會更改到參照的物件

Struct inside Struct

推薦: https://ithelp.ithome.com.tw/articles/10227592

把func 加入到 struct內

有兩種方法:

第一種:

直接放入 struct

第二種:

之後寫 func ,然後將 struct 放在 func 名稱前

https://go.dev/tour/methods/4

例如原本要把參數傳進去才能呼叫 test :

可以改為以下:讓test 變成 conn 的方法

Value receiver, Pointer receiver

這邊要注意 connection 與 *connection 傳入時有分

https://matthung0807.blogspot.com/2021/06/go-value-receiver-pointer-receiver-difference.html

Func 傳值與傳址

The first returns a copy of the struct, the second a pointer to the struct value created within the function, the third expects an existing struct to be passed in and overrides the value.

https://stackoverflow.com/questions/23542989/pointers-vs-values-in-parameters-and-return-values

iterate struct 內的值

引入其他 package 的 struct

./user/schema.go

main.go

Last updated

Was this helpful?