Go方法定义

来源:互联网 发布:mac用的vpn 编辑:程序博客网 时间:2024/05/21 17:18

A method is a function with a receiver. A method declaration binds an identifier, the method name, to a method, and associates the method with the receiver's base type.


语法格式如下:

func (Receiver) MethodName([参数列表]) [返回值列表] {

//方法体
}


The receiver is specified via an extra parameter section preceding the method name. That parameter section must declare a single non-variadic parameter, the receiver. Its type must be of the form T or *T (possibly using parentheses) where T is a type name. The type denoted by T is called the receiver base type; it must not be a pointer or interface type and it must be declared in the same package as the method. The method is said to be bound to the base type and the method name is visible only within selectors for type T or *T.


A non-blank receiver identifier must be unique in the method signature. If the receiver's value is not referenced inside the body of the method, its identifier may be omitted in the declaration. The same applies in general to parameters of functions and methods.


For a base type, the non-blank names of methods bound to it must be unique. If the base type is a struct type, the non-blank method and field names must be distinct.

Given type Point, the declarations

func (p *Point) Length() float64 {return math.Sqrt(p.x * p.x + p.y * p.y)}func (p *Point) Scale(factor float64) {p.x *= factorp.y *= factor}

bind the methods Length and Scale, with receiver type *Point, to the base type Point.

The type of a method is the type of a function with the receiver as first argument. For instance, the method Scale has type

func(p *Point, factor float64)

However, a function declared this way is not a method.

上面标红色的这段话说得很清楚,方法是函数的一种特殊类型,该函数使用接收器作为第一个参数,但是如果将函数声明成func FunctionName(receiver,其他参数列表)则该函数不是方法。正确的格式是func (Receiver)  FunctionName(其他参数列表)

下面进行案例说明。

例子1: test.go

package main


import "fmt"


type INTEGER int//自定义类型INTEGER

/*

1.为INTEGER类型添加add方法

2.这里的接收器为a,类型是INTEGER,基类型是INTEGER

*/

func (a INTEGER) add(b INTEGER) (sum INTEGER) {
sum = a+b
return sum
}


func main() {
var c INTEGER = 10
fmt.Println(c.add(20))
}

运行:

E:\project\go>go build test.go


E:\project\go>test
30

例子2:test.go

package main


import "fmt"


type INTEGER int//自定义类型INTEGER

/*

1、为INTEGER类型添加add方法

2、这里接收器的名字是a,类型是* INTEGER,指针类型。基类型是INTEGER

*/


func (a *INTEGER) add(b INTEGER) {
*a=*a+b
}


func main() {
var c INTEGER = 10
fmt.Println("Before call add method:")
fmt.Println("c=",c)
fmt.Println("After call add method:")
c.add(40)
fmt.Println("c=",c)
}

运行:

E:\project\go>go build test.go


E:\project\go>test
Before call add method:
c= 10
After call add method:
c= 50

0 0