Go的面向对象

构造函数

returning value or pointer in Go constructor?

方法与接收器

方法与函数

面向过程中没有“方法”概念,只能通过结构体和函数,由使用者使用函数参数和调用关系来形成接近“方法”的概念。而Go中的方法是作用在接收器上的一个函数,因此是一种特殊类型的函数。

指针接收器与值接收器

  • 指针接收器由于指针的特性,调用方法时,修改接收器指针的任意成员变量,在方法结束后,修改都是有效的。
  • 当方法作用于非指针接收器时,Go语言会在代码运行时将接收器的值复制一份,在非指针接收器的方法中可以获取接收器的成员值,但修改后无效。
  • 在计算机中,小对象由于值复制时的速度较快,所以适合使用非指针接收器,大对象因为复制性能较低,适合使用指针接收器,在接收器和参数间传递时不进行复制,只是传递指针。

方法调用

  • The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T). method sets
  • A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &x's method set contains mx.m() is shorthand for (&x).m().  spec: calls

猜你喜欢

转载自blog.csdn.net/qq_34276652/article/details/119676464