This repository was archived by the owner on Feb 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathparts3.go
More file actions
81 lines (69 loc) · 1.82 KB
/
Copy pathparts3.go
File metadata and controls
81 lines (69 loc) · 1.82 KB
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
// ############## Page 176-182 ##############
package main
import "fmt"
/*
Bicycle
Automatic delegation to Spares() is provided by Parts.
*/
type Bicycle struct {
Size string
Parts
}
/*
Parts
Parts is a slice vs. a struct containing one, giving it slice like behavior.
(like on Page 173)
*/
type Parts []Part
func (parts Parts) Spares() (spares Parts) {
for _, part := range parts {
if part.NeedsSpare {
spares = append(spares, part)
}
}
return spares
}
/*
Part
I don't see much need for a PartsFactory to convert an array to objects. Go's
composite literal syntax can use either name:values or just values, with the one
gotcha that all parameters must be specified with the later syntax.
*/
type Part struct {
Name string
Description string
NeedsSpare bool
}
var (
RoadBikeParts = Parts{
{"chain", "10-speed", true},
{"tire_size", "23", true},
{"tape_color", "red", true},
}
MountainBikeParts = Parts{
{"chain", "10-speed", true},
{"tire_size", "2.1", true},
{"front_shock", "Manitou", false},
{"rear_shock", "Fox", true},
}
RecumbentBikeParts = Parts{
{"chain", "9-speed", true},
{"tire_size", "28", true},
{"flag", "tall and orange", true},
}
)
func main() {
roadBike := Bicycle{Size: "L", Parts: RoadBikeParts}
mountainBike := Bicycle{Size: "L", Parts: MountainBikeParts}
recumbentBike := Bicycle{Size: "L", Parts: RecumbentBikeParts}
fmt.Println(roadBike.Spares())
fmt.Println(mountainBike.Spares())
fmt.Println(recumbentBike.Spares())
// We can combine Parts and still call Spares, unlike the Ruby example. (page 173)
comboParts := Parts{}
comboParts = append(comboParts, mountainBike.Parts...)
comboParts = append(comboParts, roadBike.Parts...)
comboParts = append(comboParts, recumbentBike.Parts...)
fmt.Println(len(comboParts))
fmt.Println(comboParts.Spares())
}