forked from PacktPublishing/Mastering-Go-Second-Edition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeyValue.go
113 lines (101 loc) · 1.84 KB
/
keyValue.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
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
type myElement struct {
Name string
Surname string
Id string
}
var DATA = make(map[string]myElement)
func ADD(k string, n myElement) bool {
if k == "" {
return false
}
if LOOKUP(k) == nil {
DATA[k] = n
return true
}
return false
}
func DELETE(k string) bool {
if LOOKUP(k) != nil {
delete(DATA, k)
return true
}
return false
}
func LOOKUP(k string) *myElement {
_, ok := DATA[k]
if ok {
n := DATA[k]
return &n
} else {
return nil
}
}
func CHANGE(k string, n myElement) bool {
DATA[k] = n
return true
}
func PRINT() {
for k, d := range DATA {
fmt.Printf("key: %s value: %v\n", k, d)
}
}
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
text := scanner.Text()
text = strings.TrimSpace(text)
tokens := strings.Fields(text)
switch len(tokens) {
case 0:
continue
case 1:
tokens = append(tokens, "")
tokens = append(tokens, "")
tokens = append(tokens, "")
tokens = append(tokens, "")
case 2:
tokens = append(tokens, "")
tokens = append(tokens, "")
tokens = append(tokens, "")
case 3:
tokens = append(tokens, "")
tokens = append(tokens, "")
case 4:
tokens = append(tokens, "")
}
switch tokens[0] {
case "PRINT":
PRINT()
case "STOP":
return
case "DELETE":
if !DELETE(tokens[1]) {
fmt.Println("Delete operation failed!")
}
case "ADD":
n := myElement{tokens[2], tokens[3], tokens[4]}
if !ADD(tokens[1], n) {
fmt.Println("Add operation failed!")
}
case "LOOKUP":
n := LOOKUP(tokens[1])
if n != nil {
fmt.Printf("%v\n", *n)
}
case "CHANGE":
n := myElement{tokens[2], tokens[3], tokens[4]}
if !CHANGE(tokens[1], n) {
fmt.Println("Update operation failed!")
}
default:
fmt.Println("Unknown command – please try again!")
}
}
}