First, the method
When a function is declared, a variable is placed before its name, which is a method. This additional parameter attaches the function to this type, which is equivalent to defining an exclusive method for the type. Such as:
Package geometryimport ' math ' type point struct{X, Y float64}//traditional Functionfunc Distance (p, Q point) float64 {
return Math. Hypot (q.x-p.x, q.y-p.y)}//same thing, but as-a method of the point Typefunc (P-point) Distance (Q-point) float64 { ret Urn Math. Hypot (q.x-p.x, q.y-p.y)}p: = Point{1, 2}q: = Point{4, 6}fmt. Println (Distance (P, Q))//"5", function callfmt. Println (P.distance (q)) //"5", Method call
The additional parameter p in the above code is called the receiver of the method. The go language does not use this or self as a receiver in other languages, and we can choose the name of the receiver. To maintain consistency and brevity when passing between methods, it is recommended to use the first letter of its type.
When the receiver variable itself is relatively large (the copy consumes more resources), we can declare the method with its pointer instead of the object. Such as:
Func (P *point) Scaleby (factor float64) { p.x *= factor p.y *=-factor}p : = Point{1, 2} (&P). Scaleby (2) fmt. PRINTLN (P)//"{2, 4}"
If the receiver p is a variable of point type, and its method requires a point pointer as a sink, we can abbreviate to P. Scaleby (2). The compiler implicitly helps us to invoke the Scaleby method with &p.
This shorthand applies only to "variables" and cannot be invoked through a receiver that cannot get an address, such as: Point{1,2}.scaleby (2).
There is no class keyword like C + + in the Go language, as well as direct object inheritance. However, you can extend the type by embedding the struct, and an anonymous field embedded in the type can be a pointer to a named type. As follows:
Type coloredpoint struct { *point color. RGBA}
Cond
Object-oriented (OOP) for the Go language