-
Notifications
You must be signed in to change notification settings - Fork 0
/
playground2.go
159 lines (130 loc) · 2.17 KB
/
playground2.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
)
func main() {
tutorial7()
tutorial8()
tutorial11()
}
type Inner2 struct {
A int
}
func (i Inner2) IntPrinter(val int) string {
return fmt.Sprintf("Inner2: %d", val)
}
func (i Inner2) Double() string {
return i.IntPrinter(i.A * 2)
}
type Outer3 struct {
Inner2
S string
}
func (o Outer3) IntPrinter(val int) string {
return fmt.Sprintf("Outer: %d", val)
}
func tutorial7() {
o := Outer3{
Inner2: Inner2{
A: 10,
},
S: "Hello",
}
fmt.Println(o.Double())
}
type LogicProvider struct {
}
func (lp LogicProvider) Process(data string) string {
// 商業邏輯
return ""
}
type Logic interface {
Process(data string) string
}
type Client struct {
L Logic
}
func (c Client) Program() {
// 從某處取得資料
//c.L.Process(data)
}
func tutorial8() {
c := Client{
L: LogicProvider{},
}
c.Program()
}
type Reader interface {
Read(p []byte) (n int, err error)
}
type Closer interface {
Closer() error
}
type ReadCloser interface {
Reader
Closer
}
var i interface{}
func tutorial9() {
i = 20
i = "hello"
i = struct {
FirstName string
LastName string
}{"Fred", "Fredson"}
}
func tutorial10() {
data := map[string]interface{}{}
contents, err := ioutil.ReadFile("testdata/sample.json")
if err != nil {
//return err
}
//defer contents.Close()
json.Unmarshal(contents, &data)
}
type LinkedList struct {
Value interface{}
Next *LinkedList
}
// Not Good
func (ll *LinkedList) Insert(pos int, val interface{}) *LinkedList {
if ll == nil || pos == 0 {
return &LinkedList{
Value: val,
Next: ll,
}
}
//ll.Next == ll.Next.Insert(pos-1, val)
return ll
}
type MyInt int
func tutorial11() {
var i interface{}
var mine MyInt = 20
i = mine
i2 := i.(MyInt)
fmt.Println(i2 + 1)
}
func doThings(i interface{}) {
switch j := i.(type) {
case nil:
case int:
fmt.Println("%d", j)
case MyInt:
case io.Reader:
case string:
case bool, rune:
default:
}
}
type Handler interface {
ServeHTTP(http.ResponseWriter, *http.Request)
}
type HandlerFunc func(http.ResponseWriter, *http.Request)
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f(w, r)
}