Methods {.en}

方法 {.zh}

::: {.en} Go supports methods defined on struct types. :::

::: {.zh}

Go 支持在结构体类型中定义方法(methods)。

:::

  1. package main
  2. import "fmt"
  3. type rect struct {
  4. width, height int
  5. }

::: {.en} This area method has a receiver type of *rect. :::

::: {.zh}

这个 area 方法有一个接收器(receiver)类型 *rect

:::

  1. func (r *rect) area() int {
  2. return r.width * r.height
  3. }

::: {.en} Methods can be defined for either pointer or value receiver types. Here’s an example of a value receiver. :::

::: {.zh}

可以为指针或值类型的接收器定义方法。这是一个值类型接收器的例子。

:::

  1. func (r rect) perim() int {
  2. return 2*r.width + 2*r.height
  3. }
  4. func main() {
  5. r := rect{width: 10, height: 5}

::: {.en} Here we call the 2 methods defined for our struct. :::

::: {.zh}

这里我们调用为结构体定义的 2 个方法。

:::

  1. fmt.Println("area: ", r.area())
  2. fmt.Println("perim:", r.perim())

::: {.en} Go automatically handles conversion between values and pointers for method calls. You may want to use a pointer receiver type to avoid copying on method calls or to allow the method to mutate the receiving struct. :::

::: {.zh}

Go 自动处理方法调用时的值和指针之间的转化。你可以使 用指针来调用方法来避免在方法调用时产生一个拷贝,或者 让方法能够改变接受的结构体。

:::

  1. rp := &r
  2. fmt.Println("area: ", rp.area())
  3. fmt.Println("perim:", rp.perim())
  4. }
  1. $ go run methods.go
  2. area: 50
  3. perim: 30
  4. area: 50
  5. perim: 30

::: {.en} Next we’ll look at Go’s mechanism for grouping and naming related sets of methods: interfaces. :::

::: {.zh}

接下来我们将介绍 Go 用于分组和命名相关 方法集合的机制:接口。

:::