那麽 ... 要如何改动 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 方式是最好的写法。
前一篇有提到在 function component 没有 this,不能使用 this.state...
该文章同步发布於:我的部落格 昨天的文章介绍了 TDD 的流程和精神等等。 今天我们要正式进入 R...
物件 物件简单来说是值与属性的配对,属性也可以是另一个物件。 之前有稍微提过建立物件有两种方法: 1...
缘由: UIUX提出说想让App使用者的手机可以一直亮着,不会自动锁屏,虽然心里知道是有可能的,但没...
前言 非常感谢六角学院在今年疫情最严重的5、6月份,提供了一系列的线上体验学习课程,能够从课程中,再...