Skip to content

# hantmac/Mastering_Go_ZH_CN

Fetching contributors…
Cannot retrieve contributors at this time
104 lines (84 sloc) 2.37 KB

# 接口的使用

`useInterface.go`的第一部分在以下Go代码中：

```package main

import (
"fmt"
"math"
"myInterface"
)

type square struct {
X float64
}

type circle struct {
R float64
}```

`useInterface.go`的第二个代码部分包含以下代码：

```func (s square) Area() float64 {
return s.X * s.X
}

func (s square) Perimeter() float64 {
return 4 * s.X
}```

```func (s circle) Area() float64 {
return s.R * s.R * math.Pi
}

func (s circle) Perimeter() float64 {
return 2 * s.R * math.Pi
}```

`useInterface.go`的第四部分包含以下Go代码：

```func Calculate(x myInterface.Shape) {
_, ok := x.(circle)
if ok {
fmt.Println("Is a circle!")
}

v, ok := x.(square)
if ok {
fmt.Println("Is a square:", v)
}

fmt.Println(x.Area())
fmt.Println(x.Perimeter())
}```

```func main() {
x := square{X: 10}
fmt.Println("Perimeter:", x.Perimeter())
Calculate(x)
y := circle{R: 5}
Calculate(y)
}```

```\$ go run useInterface.go
Perimeter: 40
Is a square: {10}
100
40
Is a circle!
78.53981633974483
31.41592653589793```
You can’t perform that action at this time.