1.如何實例化對象
傳址方式
注意:傳址是PHP中默認(rèn)使用的方式,例如 $a=new b()
- rect1 := new(Rect)
- rect2 := &Rect{}
傳值方式
注意:PHP中要實現(xiàn)傳值,需要使用clone關(guān)鍵字,go中直接賦值的方式是傳值
- a := Rect{}
2.調(diào)用對象的方法,先看如下代碼
simple.go
type SimpleEngine struct {
}
func (this *SimpleEngine) Run(seeds ...Request) {}
main.go
func main() {
engine.SimpleEngine{}.Run()
}
在main中直接調(diào)用run會報錯:
cannot call pointer method on engine.SimpleEngine literal
cannot take the address of engine.SimpleEngine literal
原因是Run方法的接受者是指針,相當(dāng)于PHP對象的方法,必須要實例化對象后才能調(diào)用,而如果想要通過engine.SimpleEngine{}.Run()直接調(diào)用,就需要將Run方法的接受者定義為
type SimpleEngine struct {
}
func (this SimpleEngine) Run(seeds ...Request) {}
此時Run方法相當(dāng)于靜態(tài)函數(shù),不用實例化對象就可以直接調(diào)用此方法