-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
251 lines (205 loc) · 5.33 KB
/
main.go
File metadata and controls
251 lines (205 loc) · 5.33 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
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"regexp"
"sync"
"time"
"unicode/utf8"
)
var argFile string
func main() {
fmt.Println("Hello Me! Let's continue learning !")
flag.StringVar(&argFile, "file", "", "If given, filename part is printed.")
flag.Parse()
args()
splitFilename(argFile)
utf8Sample()
arrays()
sliceGotcha()
// clojure().Wait()
dynamicJsonUnmarshal()
jsonDecoderEncoder()
}
func args() {
fmt.Printf("\n=== Args ===\n")
args := os.Args
fmt.Printf("Args: V:%#v \n", args)
}
func splitFilename(filename string) {
fmt.Printf("\n=== Split Filename ===\n")
if filename == "" {
filename = "/home/dev/img/avatar.jpg"
fmt.Println("Filename is set to: \"/home/img/avatar.jpg")
fmt.Println("Different filename can be provided with --file param.")
}
_, path := path.Split(filename)
fmt.Println("Filename:", filename, "full-path:", path)
}
func utf8Sample() {
// Go source code is always utf-8.
// A string in go is read-only slice of arbitrary bytes; not have to unicode text.
// A string literal always holds valid UTF-8 sequences.
// len(s) returns number of bytes; not length of text.
// using 'for i,r := range s ...' iterates over runes, not bytes.
fmt.Printf("\n=== UTF-8 ===\n")
const nihongo = "日本語"
fmt.Println("Sample string:", nihongo)
for i, w := 0, 0; i < len(nihongo); i += w {
runeValue, width := utf8.DecodeRuneInString(nihongo[i:])
fmt.Printf("%#U starts at byte position %d\n", runeValue, i)
w = width
}
// Above for loop can also be write simply as
/*
for i, r := range nihongo {
fmt.Printf("%#U starts at byte position %d\n", r, i)
}
*/
fmt.Printf("日本語 => len: %d runes: %d\n", len(nihongo), utf8.RuneCountInString(nihongo))
}
func arrays() {
fmt.Printf("\n=== Arrays ===\n")
// Arrays are value types, and their types also include length.
// So their size can not be changed in runtime. Length belongs compile time.
seasons := [4]string{"summer", "fall", "winter", "sprint"}
// Since arrays are values, in assignments they are copied.
// Also in for...range operations, they are copied again;
copy := seasons
copy[1] = "autumn"
fmt.Printf("Org: %#v\n", seasons)
fmt.Printf("Copy: %#v\n", copy)
}
func sliceGotcha() {
fmt.Printf("\n=== Slice Gotcha ===\n")
const s = "You need to find me somehow!"
b, err := ioutil.ReadFile("./main.go")
if err != nil {
panic("Could not read main.go")
}
x := regexp.MustCompile(`(?m:^.*somehow.*$)`)
b2 := x.Find(b)
/*
When you create a slice, they both point to the same array.
If original slice is much bigger than child slice, and
if you don't need original slice but smaller child slice,
you better copy smaller slice to new slice then return it.
*/
// Gotcha here is 'b2' slice' is created from 'b' slice.
// Underneath, they point point to the same array, which hold all file content.
// So for a single line, we keep whole document in the memory.
fmt.Printf("Matched line: %q\n", string(b2))
fmt.Printf("capacity: %v\n", cap(b))
// Solution is, before returing the matched line, we need to copy it.
b3 := append([]byte(nil), b2...)
fmt.Printf("Copied line: %q (Actually hold all main.go lines in the memory)\n", string(b3))
fmt.Printf("capacity: %v (Only a single line remains in memory)\n", cap(b3))
}
func clojure() *sync.WaitGroup {
fmt.Printf("\n=== Clojures in Go ===\n")
fmt.Println()
var wgx sync.WaitGroup
wgx.Add(1)
go func() {
local := 1
var wg sync.WaitGroup
// Anonymous function with local closure
f := func() {
fmt.Println(local)
}
// Print local in each second
wg.Add(1)
go func() {
defer wg.Done()
done := make(chan bool, 1)
ticker := time.NewTicker(1 * time.Second)
for {
select {
case <-ticker.C:
f()
if local > 5 {
ticker.Stop()
done <- true
}
case <-done:
return
}
}
}()
// Increment local in each second
wg.Add(1)
go func() {
defer wg.Done()
done := make(chan bool, 1)
ticker := time.NewTicker(1 * time.Second)
// When ticker.Stop is called; ticker is stopped but
// it does not close the ticker channel. so "range" not works
// This is why we use just "for"
for {
select {
case <-ticker.C:
local += 1
if local > 5 {
ticker.Stop()
done <- true
}
case <-done:
return
}
}
}()
wg.Wait()
wgx.Done()
}()
return &wgx
}
func dynamicJsonUnmarshal() {
b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"], "isFemale": true}`)
var f interface{}
err := json.Unmarshal(b, &f)
if err != nil {
fmt.Printf("unmarshal error: %v", err.Error())
return
}
fmt.Printf("json: %+v \n", f)
j := f.(map[string]interface{})
for k, v := range j {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string", vv)
case float64:
fmt.Println(k, "is float64", vv)
case []interface{}:
fmt.Println(k, "is array")
for i, u := range vv {
fmt.Println(k, "=> item:", i, u)
}
default:
fmt.Println("alien item:", k)
}
}
}
func jsonDecoderEncoder() {
dec := json.NewDecoder(os.Stdin)
enc := json.NewEncoder(os.Stdout)
for {
var v map[string]interface{}
if err := dec.Decode(&v); err != nil {
log.Panicln(err)
return
}
for k := range v {
if k != "Name" {
delete(v, k)
}
}
if err := enc.Encode(&v); err != nil {
log.Println(err)
}
}
}