iT邦幫忙

2021 iThome 鐵人賽

DAY 9
1
Modern Web

還喝不 go系列 第 9

[13th][Day9] Pointer-1

那麼 ... 要如何改動 House.price 的『值』呢?

package main

import "fmt"

type House struct {
    Name  string
    Price int
}

func (c House) GetPrice() {
    fmt.Println("price:", c.Price)
}

func (c House) UpdatePrice(price int) *House {
    c.Price = price
    return &c
}

func main() {
    h := &House{"Dibao", 100000000}
    h.GetPrice()
    h = h.UpdatePrice(10000)
    h.GetPrice()
}

可以將『整個』 struct 回傳,以取得修改後的值。

or ... 來試試看用 Pointer 的方式

package main

import "fmt"

type House struct {
    Name  string
    Price int
}

func (c House) GetPrice() {
    fmt.Println("price:", c.Price)
}

func (c House) UpdatePrice(price int) {
    fmt.Println("[value] Update Price to", price)
    c.Price = price
}

func (c *House) UpdatePricePointer(price int) {
    fmt.Println("[pointer] Update Price to", price)
    c.Price = price
}

func main() {
    h := &House{"Dibao", 100000000}
    h.GetPrice()
    h.UpdatePrice(10000)
    fmt.Println(h)
    h.UpdatePricePointer(10000)
    fmt.Println(h)
}

輸出

price: 100000000
[value] Update Price to 10000
&{Dibao 100000000}
[pointer] Update Price to 10000
&{Dibao 10000}

func (c *House) UpdatePricePointer(price int)
用 pointer 方式傳值給 method 就可以正確將需要改變的值寫入

目前為止測試的結果是:如果只想要讀值,可以單純使用 Value 或 Pointer 方式,但若是要寫入,則需要用能用 Pointer 方式傳入。

在 Effective Go 中有詳細的整理,有在看英文文件的朋友們可以嘗試吸收看看
https://golang.org/doc/effective_go.html#methods

小結
write 或 read
若要對 Struct 內的成員進行修改,那請使用 Pointer 傳值,相反的,Go 會使用 Copy struct 方式來傳入,但是用此方式你就拿不到修改後的資料。

可讀性
假設 Struct 內部成員非常的多,請使用 Pointer 方式傳入,func 的參數也會好寫很多。

一致性
在多人協同開發時,若是 ... 有人使用 Pointer 、有人使用 Value 方式,這樣寫法不統一,提升維護困難度、降低維護效率,so ... 官方建議,全部使用 Pointer 方式是最好的寫法。


上一篇
[13th][Day8] Pointer
下一篇
[13th][Day10] waiting group
系列文
還喝不 go23
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言