x
 
1
// _Interfaces_ are named collections of method
2
// signatures.
3
4
package main
5
6
import "fmt"
7
import "math"
8
9
// Here's a basic interface for geometric shapes.
10
type geometry interface {
11
    area() float64
12
    perim() float64
13
}
14
15
// For our example we'll implement this interface on
16
// `square` and `circle` types.
17
type square struct {
18
    width, height float64
19
}
20
type circle struct {
21
    radius float64
22
}
23
24
// To implement an interface in Go, we just need to
25
// implement all the methods in the interface. Here we
26
// implement `geometry` on `square`s.
27
func (s square) area() float64 {
28
    return s.width * s.height
29
}
30
func (s square) perim() float64 {
31
    return 2*s.width + 2*s.height
32
}
33
34
// The implementation for `circle`s.
35
func (c circle) area() float64 {
36
    return math.Pi * c.radius * c.radius
37
}
38
func (c circle) perim() float64 {
39
    return 2 * math.Pi * c.radius
40
}
41
42
// If a variable has an interface type, then we can call
43
// methods that are in the named interface. Here's a
44
// generic `measure` function taking advantage of this
45
// to work on any `geometry`.
46
func measure(g geometry) {
47
    fmt.Println(g)
48
    fmt.Println(g.area())
49
    fmt.Println(g.perim())
50
}
51
52
func main() {
53
    s := square{width: 3, height: 4}
54
    c := circle{radius: 5}
55
56
    // The `circle` and `square` struct types both
57
    // implement the `geometry` interface so we can use
58
    // instances of
59
    // these structs as arguments to `measure`.
60
    measure(s)
61
    measure(c)
62
}
63
分享