-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path09_slice_of_interfaces.go
84 lines (72 loc) · 2.05 KB
/
09_slice_of_interfaces.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Seriál "Programovací jazyk Go"
// https://www.root.cz/serialy/programovaci-jazyk-go/
//
// Čtvrtá část
// Rozhraní, metody, gorutiny a kanály v programovacím jazyku Go
// https://www.root.cz/clanky/rozhrani-metody-gorutiny-a-kanaly-v-programovacim-jazyku-go/
//
// Repositář:
// https://github.com/tisnik/go-root/
//
// Seznam demonstračních příkladů ze čtvrté části:
// https://github.com/tisnik/go-root/blob/master/article_04/README.md
//
// Demonstrační příklad číslo 9:
// Řez s objekty implementující rozhraní.
//
// Dokumentace ve stylu "literate programming":
// https://tisnik.github.io/go-root/article_04/09_slice_of_interfaces.html
package main
import (
"fmt"
"math"
)
// ClosedShape je uživatelsky definovaná datová struktura
// představující uzavřené geometrické tvary (úsečka, oblouk, křivka)
type ClosedShape interface {
area() float64
}
func area(shape ClosedShape) float64 {
return shape.area()
}
// Circle je uživatelsky definovaná datová struktura
// představující kružnici se středem v bodě [x, y]
// a poloměrem radius
type Circle struct {
x, y float64
radius float64
}
// Ellipse je uživatelsky definovaná datová struktura
// představující elipsu se středem v bodě [x, y]
// a poloměrem poloos a a b
type Ellipse struct {
x, y float64
a, b float64
}
// Rectangle je uživatelsky definovaná datová struktura
// představující geometrický tvar obdélníka
type Rectangle struct {
x, y float64
width, height float64
}
func (rect Rectangle) area() float64 {
return rect.width * rect.height
}
func (circle Circle) area() float64 {
return math.Pi * circle.radius * circle.radius
}
func (ellipse Ellipse) area() float64 {
return math.Pi * ellipse.a * ellipse.b
}
func main() {
shapes := []ClosedShape{
Rectangle{x: 0, y: 0, width: 100, height: 100},
Circle{x: 0, y: 0, radius: 100},
Ellipse{x: 0, y: 0, a: 100, b: 50}}
for _, shape := range shapes {
fmt.Println(shape)
fmt.Println(area(shape))
fmt.Println(shape.area())
fmt.Println()
}
}