-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathembed.slide
110 lines (71 loc) · 1.61 KB
/
embed.slide
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
Embedding
Matthew Heidemann
Pivotal Tracker
@heidmotron
* Definition
Go does not provide the typical, type-driven notion of subclassing, but it does have the ability to “borrow” pieces of an implementation by embedding types within a struct or interface.
* Where have you seen this before?
type ReadWriter interface {
Reader
Writer
}
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
* Basics
- How do we define types?
type Story struct {
Id int64
Title string
State string
}
type Foo int64
* Defining methods
type Story struct {
Id int64
Title string
}
// Value Receivers
func (s Story) isNew() bool {
return s.Id == 0
}
// Pointer Receivers
func (s *Story) Url() string {
url := "/services/v5/stories"
if !s.IsNew() {
url = fmt.Sprintf("%s/%d", url, s.Id)
}
return url
}
* So now what?
Let's say we have 3 more models that need IsNew behavior:
type Project struct {
Id int64
}
type Task struct {
Id int64
}
type Comment struct {
Id int64
}
How should we do this? Copy-Pasta
* In other languages ruby, java, js
Define some abstract Model class with `IsNew` behavior
// backbone.js
Backbone.Model = function(attributes, options) {
...
isNew: function() {
return this.id == null;
},
...
}
* Let's embed
It's about composition, we now get all of `Id's` methods on the `Story`
.play embed/1.go
* This will work for more complex types
.play embed/c.go
* How do we override
.play embed/2.go