1.如何实例化对象
传址方式
注意:传址是PHP中默认使用的方式,例如 $a=new b()
- rect1 := new(Rect)
- rect2 := &Rect{}
传值方式
注意:PHP中要实现传值,需要使用clone关键字,go中直接赋值的方式是传值
- a := Rect{}
2.调用对象的方法,先看如下代码
simple.go
type SimpleEngine struct {
}
func (this *SimpleEngine) Run(seeds ...Request) {}
main.go
func main() {
engine.SimpleEngine{}.Run()
}
在main中直接调用run会报错:
cannot call pointer method on engine.SimpleEngine literal
cannot take the address of engine.SimpleEngine literal
原因是Run方法的接受者是指针,相当于PHP对象的方法,必须要实例化对象后才能调用,而如果想要通过engine.SimpleEngine{}.Run()直接调用,就需要将Run方法的接受者定义为
type SimpleEngine struct {
}
func (this SimpleEngine) Run(seeds ...Request) {}
此时Run方法相当于静态函数,不用实例化对象就可以直接调用此方法
网友评论