Interfaces {.en}

接口 {.zh}

::: {.en} Interfaces are named collections of method signatures. :::

::: {.zh}

接口(Interfaces)是命名了的方法签名(signatures) 的集合。

:::

  1. package main
  2. import "fmt"
  3. import "math"

::: {.en} Here’s a basic interface for geometric shapes. :::

::: {.zh}

这是一个几何形状的基本接口。

:::

  1. type geometry interface {
  2. area() float64
  3. perim() float64
  4. }

::: {.en} For our example we’ll implement this interface on rect and circle types. :::

::: {.zh}

对于我们的示例,我们将在类型 rectcircle 上实现此接口。

:::

  1. type rect struct {
  2. width, height float64
  3. }
  4. type circle struct {
  5. radius float64
  6. }

::: {.en} To implement an interface in Go, we just need to implement all the methods in the interface. Here we implement geometry on rects. :::

::: {.zh}

要在 Go 中实现接口,我们只需要实现接口中的所有方法。这里我们在 rect 上实现 geometry 接口。

:::

  1. func (r rect) area() float64 {
  2. return r.width * r.height
  3. }
  4. func (r rect) perim() float64 {
  5. return 2*r.width + 2*r.height
  6. }

::: {.en} The implementation for circles. :::

::: {.zh}

circle 的实现。

:::

  1. func (c circle) area() float64 {
  2. return math.Pi * c.radius * c.radius
  3. }
  4. func (c circle) perim() float64 {
  5. return 2 * math.Pi * c.radius
  6. }

::: {.en} If a variable has an interface type, then we can call methods that are in the named interface. Here’s a generic measure function taking advantage of this to work on any geometry. :::

::: {.zh}

如果变量具有接口类型,那么我们可以调用指定接口中的方法。这里有一个通用 measure 函数,利用它来在任何 geometry 上工作。

:::

  1. func measure(g geometry) {
  2. fmt.Println(g)
  3. fmt.Println(g.area())
  4. fmt.Println(g.perim())
  5. }
  6. func main() {
  7. r := rect{width: 3, height: 4}
  8. c := circle{radius: 5}

::: {.en} The circle and rect struct types both implement the geometry interface so we can use instances of these structs as arguments to measure. :::

::: {.zh}

结构体类型 circlerect 都实现了 geometry 接口,所以我们可以使用这些结构体的实例作为 measure 的参数。

:::

  1. measure(r)
  2. measure(c)
  3. }
  1. $ go run interfaces.go
  2. {3 4}
  3. 12
  4. 14
  5. {5}
  6. 78.53981633974483
  7. 31.41592653589793

::: {.en} To learn more about Go’s interfaces, check out this great blog post. :::

::: {.zh}

要了解有关 Go 的接口的更多信息,请查看 很棒的博客文章

:::