# 07.1 类型方法

Go的**类型方法**是带有特殊参数的函数。在一个声明为普通函数的方法函数名前面，增加一个特定参数，该特定参数将函数与该参数的类型进行关联，该特定参数被称为**方法的接收器**。

下面的Go代码是在<https://golang.org/src/os/file_plan9.go>中的`Close()`函数的实现：

> ```go
> func (f *File) Close() error {
>     if err := f.checkValid("close"); err != nil {
>         return err
>     }
>     return f.file.close()
> }
> ```

`Close()`函数就是**类型方法**，因为函数名称前面和`func`关键字后面有`(f *File)`参数。`f`参数被称为**方法的接收器**；在面向对象编程术语中，这个过程可以描述为向**对象**发送消息。在Go语言中，**方法的接收器**是使用常规变量名定义的，通常使用单个字母，而不需要使用专用关键字，如`this`或`self`。

接下来我们使用`methods.go`文件的Go代码来呈现一个完整的示例，包含以下四部分。

````
> ```go
> package main
> 
> import (
>     "fmt"
> )
> 
> type twoInts struct {
>     X int64
>     Y int64
> }
>
````

在前面的代码中，定义了结构体`twoInts`，该结构体包含两个`int64`类型的字段。

````
> ```go
> func regularFunction(a, b twoInts) twoInts {
>     temp := twoInts{X: a.X + b.X, Y: a.Y + b.Y}
>     return temp
> }
>
````

在本部分中，定义了一个名为`regularFunction()`的函数，该函数接收两个`twoInts`类型的参数，并返回一个`twoInts`类型的值。

````
> ```go
> func (a twoInts) method(b twoInts) twoInts {
>     temp := twoInts{X: a.X + b.X, Y: a.Y + b.Y}
>     return temp
> }
>
````

````
> _这里真正有趣的是，**类型方法**```method()```与普通函数```regularFunction()```的实现完全相同。_

```methods.go```的最后一个代码段如下：

> ```go
> func main() {
>     i := twoInts{X: 1, Y: 2}
>     j := twoInts{X: -5, Y: -2}
>     fmt.Println(regularFunction(i, j))
>     fmt.Println(i.method(j))
> }
>
````

如您所见，您调用**类型方法**（`i.method(j)`）的方式是与普通函数（`regularFunction(i，j)`）的调用方式不同。

执行`methods.go`的输出如下：

> ```
> $ go run methods.go
> {-4 0}
> {-4 0}
> ```

值得注意的是，**类型方法**也与**接口**相关，下一节中将对**接口**进行讲解，稍后也将看到更多**类型方法**的使用。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wskdsgcf.gitbook.io/mastering-go-zh-cn/7-fan-she-he-jie-kou/07.1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
