From a39cfd0b05f84270efead8fa9c2f882fac4f2de2 Mon Sep 17 00:00:00 2001 From: Mihalis Tsoukalos Date: Thu, 10 Jan 2019 22:08:08 +0200 Subject: [PATCH] ch03 + ch04 --- ch03/constants.go | 54 ++++++++++++++++++++ ch03/copySlice.go | 41 +++++++++++++++ ch03/failMap.go | 14 ++++++ ch03/lenCap.go | 30 +++++++++++ ch03/loops.go | 48 ++++++++++++++++++ ch03/parseDate.go | 26 ++++++++++ ch03/parseTime.go | 25 ++++++++++ ch03/pointers.go | 38 ++++++++++++++ ch03/reslice.go | 17 +++++++ ch03/slices.go | 41 +++++++++++++++ ch03/sortSlice.go | 32 ++++++++++++ ch03/timeDate.go | 34 +++++++++++++ ch03/usingArrays.go | 35 +++++++++++++ ch03/usingMaps.go | 35 +++++++++++++ ch03/usingTime.go | 23 +++++++++ ch04/calculatePi.go | 82 ++++++++++++++++++++++++++++++ ch04/changeDT.go | 66 ++++++++++++++++++++++++ ch04/findIPv4.go | 54 ++++++++++++++++++++ ch04/keyValue.go | 113 ++++++++++++++++++++++++++++++++++++++++++ ch04/logEntries.txt | 6 +++ ch04/pointerStruct.go | 34 +++++++++++++ ch04/runes.go | 21 ++++++++ ch04/selectColumn.go | 56 +++++++++++++++++++++ ch04/strings.go | 42 ++++++++++++++++ ch04/structures.go | 29 +++++++++++ ch04/switch.go | 65 ++++++++++++++++++++++++ ch04/tuples.go | 21 ++++++++ ch04/unicode.go | 18 +++++++ ch04/useStrings.go | 57 +++++++++++++++++++++ 29 files changed, 1157 insertions(+) create mode 100644 ch03/constants.go create mode 100644 ch03/copySlice.go create mode 100644 ch03/failMap.go create mode 100644 ch03/lenCap.go create mode 100644 ch03/loops.go create mode 100644 ch03/parseDate.go create mode 100644 ch03/parseTime.go create mode 100644 ch03/pointers.go create mode 100644 ch03/reslice.go create mode 100644 ch03/slices.go create mode 100644 ch03/sortSlice.go create mode 100644 ch03/timeDate.go create mode 100644 ch03/usingArrays.go create mode 100644 ch03/usingMaps.go create mode 100644 ch03/usingTime.go create mode 100644 ch04/calculatePi.go create mode 100644 ch04/changeDT.go create mode 100644 ch04/findIPv4.go create mode 100644 ch04/keyValue.go create mode 100644 ch04/logEntries.txt create mode 100644 ch04/pointerStruct.go create mode 100644 ch04/runes.go create mode 100644 ch04/selectColumn.go create mode 100644 ch04/strings.go create mode 100644 ch04/structures.go create mode 100644 ch04/switch.go create mode 100644 ch04/tuples.go create mode 100644 ch04/unicode.go create mode 100644 ch04/useStrings.go diff --git a/ch03/constants.go b/ch03/constants.go new file mode 100644 index 0000000..71e401b --- /dev/null +++ b/ch03/constants.go @@ -0,0 +1,54 @@ +package main + +import ( + "fmt" +) + +type Digit int +type Power2 int + +const PI = 3.1415926 + +const ( + C1 = "C1C1C1" + C2 = "C2C2C2" + C3 = "C3C3C3" +) + +func main() { + + const s1 = 123 + var v1 float32 = s1 * 12 + fmt.Println(v1) + fmt.Println(PI) + + // const s2 float64 = 123 + // var v2 float32 = s2 * 12 + + const ( + Zero Digit = iota + One + Two + Three + Four + ) + + fmt.Println(One) + fmt.Println(Two) + + const ( + p2_0 Power2 = 1 << iota + _ + p2_2 + _ + p2_4 + _ + p2_6 + ) + + fmt.Println("2^0:", p2_0) + fmt.Println("2^2:", p2_2) + fmt.Println("2^4:", p2_4) + fmt.Println("2^6:", p2_6) + +} diff --git a/ch03/copySlice.go b/ch03/copySlice.go new file mode 100644 index 0000000..0033930 --- /dev/null +++ b/ch03/copySlice.go @@ -0,0 +1,41 @@ +package main + +import ( + "fmt" +) + +func main() { + + a6 := []int{-10, 1, 2, 3, 4, 5} + a4 := []int{-1, -2, -3, -4} + fmt.Println("a6:", a6) + fmt.Println("a4:", a4) + + copy(a6, a4) + fmt.Println("a6:", a6) + fmt.Println("a4:", a4) + fmt.Println() + + b6 := []int{-10, 1, 2, 3, 4, 5} + b4 := []int{-1, -2, -3, -4} + fmt.Println("b6:", b6) + fmt.Println("b4:", b4) + copy(b4, b6) + fmt.Println("b6:", b6) + fmt.Println("b4:", b4) + + fmt.Println() + array4 := [4]int{4, -4, 4, -4} + s6 := []int{1, 1, -1, -1, 5, -5} + copy(s6, array4[0:]) + fmt.Println("array4:", array4[0:]) + fmt.Println("s6:", s6) + + fmt.Println() + + array5 := [5]int{5, -5, 5, -5, 5} + s7 := []int{7, 7, -7, -7, 7, -7, 7} + copy(array5[0:], s7) + fmt.Println("array5:", array5) + fmt.Println("s7:", s7) +} diff --git a/ch03/failMap.go b/ch03/failMap.go new file mode 100644 index 0000000..4a29561 --- /dev/null +++ b/ch03/failMap.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" +) + +func main() { + + aMap := map[string]int{} + aMap = nil + fmt.Println(aMap) + aMap["test"] = 1 + +} diff --git a/ch03/lenCap.go b/ch03/lenCap.go new file mode 100644 index 0000000..9a6369b --- /dev/null +++ b/ch03/lenCap.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" +) + +func printSlice(x []int) { + for _, number := range x { + fmt.Print(number, " ") + } + fmt.Println() +} + +func main() { + aSlice := []int{-1, 0, 4} + fmt.Printf("aSlice: ") + printSlice(aSlice) + + fmt.Printf("Cap: %d, Length: %d\n", cap(aSlice), len(aSlice)) + aSlice = append(aSlice, -100) + fmt.Printf("aSlice: ") + printSlice(aSlice) + fmt.Printf("Cap: %d, Length: %d\n", cap(aSlice), len(aSlice)) + + aSlice = append(aSlice, -2) + aSlice = append(aSlice, -3) + aSlice = append(aSlice, -4) + printSlice(aSlice) + fmt.Printf("Cap: %d, Length: %d\n", cap(aSlice), len(aSlice)) +} diff --git a/ch03/loops.go b/ch03/loops.go new file mode 100644 index 0000000..cf5899f --- /dev/null +++ b/ch03/loops.go @@ -0,0 +1,48 @@ +package main + +import ( + "fmt" +) + +func main() { + + for i := 0; i < 100; i++ { + if i%20 == 0 { + continue + } + + if i == 95 { + break + } + + fmt.Print(i, " ") + } + + fmt.Println() + i := 10 + for { + if i < 0 { + break + } + fmt.Print(i, " ") + i-- + } + fmt.Println() + + i = 0 + anExpression := true + for ok := true; ok; ok = anExpression { + if i > 10 { + anExpression = false + } + + fmt.Print(i, " ") + i++ + } + fmt.Println() + + anArray := [5]int{0, 1, -1, 2, -2} + for i, value := range anArray { + fmt.Println("index:", i, "value: ", value) + } +} diff --git a/ch03/parseDate.go b/ch03/parseDate.go new file mode 100644 index 0000000..8fdc72b --- /dev/null +++ b/ch03/parseDate.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "time" +) + +func main() { + + var myDate string + if len(os.Args) != 2 { + fmt.Printf("usage: %s string\n", filepath.Base(os.Args[0])) + return + } + + myDate = os.Args[1] + d, err := time.Parse("02 January 2006", myDate) + if err == nil { + fmt.Println("Full:", d) + fmt.Println("Time:", d.Day(), d.Month(), d.Year()) + } else { + fmt.Println(err) + } +} diff --git a/ch03/parseTime.go b/ch03/parseTime.go new file mode 100644 index 0000000..504ecd8 --- /dev/null +++ b/ch03/parseTime.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "time" +) + +func main() { + var myTime string + if len(os.Args) != 2 { + fmt.Printf("usage: %s string\n", filepath.Base(os.Args[0])) + os.Exit(1) + } + + myTime = os.Args[1] + d, err := time.Parse("15:04", myTime) + if err == nil { + fmt.Println("Full:", d) + fmt.Println("Time:", d.Hour(), d.Minute()) + } else { + fmt.Println(err) + } +} diff --git a/ch03/pointers.go b/ch03/pointers.go new file mode 100644 index 0000000..232999d --- /dev/null +++ b/ch03/pointers.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" +) + +func getPointer(n *int) { + *n = *n * *n + +} + +func returnPointer(n int) *int { + v := n * n + return &v +} + +func main() { + i := -10 + j := 25 + + pI := &i + pJ := &j + + fmt.Println("pI memory:", pI) + fmt.Println("pJ memory:", pJ) + fmt.Println("pI value:", *pI) + fmt.Println("pJ value:", *pJ) + + *pI = 123456 + *pI-- + fmt.Println("i:", i) + + getPointer(pJ) + fmt.Println("j:", j) + k := returnPointer(12) + fmt.Println(*k) + fmt.Println(k) +} diff --git a/ch03/reslice.go b/ch03/reslice.go new file mode 100644 index 0000000..e19382b --- /dev/null +++ b/ch03/reslice.go @@ -0,0 +1,17 @@ +package main + +import "fmt" + +func main() { + + s1 := make([]int, 5) + reSlice := s1[1:3] + fmt.Println(s1) + fmt.Println(reSlice) + + reSlice[0] = -100 + reSlice[1] = 123456 + fmt.Println(s1) + fmt.Println(reSlice) + +} diff --git a/ch03/slices.go b/ch03/slices.go new file mode 100644 index 0000000..52b77f7 --- /dev/null +++ b/ch03/slices.go @@ -0,0 +1,41 @@ +package main + +import ( + "fmt" +) + +func main() { + aSlice := []int{1, 2, 3, 4, 5} + fmt.Println(aSlice) + integer := make([]int, 2) + fmt.Println(integer) + + integer = nil + fmt.Println(integer) + + anArray := [5]int{-1, -2, -3, -4, -5} + refAnArray := anArray[:] + fmt.Println(anArray) + fmt.Println(refAnArray) + anArray[4] = -100 + fmt.Println(refAnArray) + + s := make([]byte, 5) + fmt.Println(s) + twoD := make([][]int, 3) + fmt.Println(twoD) + fmt.Println() + + for i := 0; i < len(twoD); i++ { + for j := 0; j < 2; j++ { + twoD[i] = append(twoD[i], i*j) + } + } + + for _, x := range twoD { + for i, y := range x { + fmt.Println("i:", i, "value:", y) + } + fmt.Println() + } +} diff --git a/ch03/sortSlice.go b/ch03/sortSlice.go new file mode 100644 index 0000000..9c3ee56 --- /dev/null +++ b/ch03/sortSlice.go @@ -0,0 +1,32 @@ +package main + +import ( + "fmt" + "sort" +) + +type aStructure struct { + person string + height int + weight int +} + +func main() { + + mySlice := make([]aStructure, 0) + mySlice = append(mySlice, aStructure{"Mihalis", 180, 90}) + mySlice = append(mySlice, aStructure{"Bill", 134, 45}) + mySlice = append(mySlice, aStructure{"Marietta", 155, 45}) + mySlice = append(mySlice, aStructure{"Epifanios", 144, 50}) + mySlice = append(mySlice, aStructure{"Athina", 134, 40}) + + fmt.Println("0:", mySlice) + sort.Slice(mySlice, func(i, j int) bool { + return mySlice[i].height < mySlice[j].height + }) + fmt.Println("<:", mySlice) + sort.Slice(mySlice, func(i, j int) bool { + return mySlice[i].height > mySlice[j].height + }) + fmt.Println(">:", mySlice) +} diff --git a/ch03/timeDate.go b/ch03/timeDate.go new file mode 100644 index 0000000..7325bcc --- /dev/null +++ b/ch03/timeDate.go @@ -0,0 +1,34 @@ +package main + +import ( + "fmt" + "regexp" + "time" +) + +func main() { + + logs := []string{"127.0.0.1 - - [16/Nov/2017:10:49:46 +0200] 325504", + "127.0.0.1 - - [16/Nov/2017:10:16:41 +0200] \"GET /CVEN HTTP/1.1\" 200 12531 \"-\" \"Mozilla/5.0 AppleWebKit/537.36", + "127.0.0.1 200 9412 - - [12/Nov/2017:06:26:05 +0200] \"GET \"http://www.mtsoukalos.eu/taxonomy/term/47\" 1507", + "[12/Nov/2017:16:27:21 +0300]", + "[12/Nov/2017:20:88:21 +0200]", + "[12/Nov/2017:20:21 +0200]", + } + + for _, logEntry := range logs { + r := regexp.MustCompile(`.*\[(\d\d\/\w+/\d\d\d\d:\d\d:\d\d:\d\d.*)\].*`) + if r.MatchString(logEntry) { + match := r.FindStringSubmatch(logEntry) + dt, err := time.Parse("02/Jan/2006:15:04:05 -0700", match[1]) + if err == nil { + newFormat := dt.Format(time.RFC850) + fmt.Println(newFormat) + } else { + fmt.Println("Not a valid date time format!") + } + } else { + fmt.Println("Not a match!") + } + } +} diff --git a/ch03/usingArrays.go b/ch03/usingArrays.go new file mode 100644 index 0000000..2f584a3 --- /dev/null +++ b/ch03/usingArrays.go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" +) + +func main() { + anArray := [4]int{1, 2, 4, -4} + twoD := [4][4]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} + threeD := [2][2][2]int{{{1, 0}, {-2, 4}}, {{5, -1}, {7, 0}}} + + fmt.Println("The length of", anArray, "is", len(anArray)) + fmt.Println("The first element of", twoD, "is", twoD[0][0]) + fmt.Println("The length of", threeD, "is", len(threeD)) + + for i := 0; i < len(threeD); i++ { + v := threeD[i] + for j := 0; j < len(v); j++ { + m := v[j] + for k := 0; k < len(m); k++ { + fmt.Print(m[k], " ") + } + } + fmt.Println() + } + + for _, v := range threeD { + for _, m := range v { + for _, s := range m { + fmt.Print(s, " ") + } + } + fmt.Println() + } +} diff --git a/ch03/usingMaps.go b/ch03/usingMaps.go new file mode 100644 index 0000000..b9e1e7d --- /dev/null +++ b/ch03/usingMaps.go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" +) + +func main() { + + iMap := make(map[string]int) + iMap["k1"] = 12 + iMap["k2"] = 13 + fmt.Println("iMap:", iMap) + + anotherMap := map[string]int{ + "k1": 12, + "k2": 13, + } + + fmt.Println("anotherMap:", anotherMap) + delete(anotherMap, "k1") + delete(anotherMap, "k1") + delete(anotherMap, "k1") + fmt.Println("anotherMap:", anotherMap) + + _, ok := iMap["doesItExist"] + if ok { + fmt.Println("Exists!") + } else { + fmt.Println("Does NOT exist") + } + + for key, value := range iMap { + fmt.Println(key, value) + } +} diff --git a/ch03/usingTime.go b/ch03/usingTime.go new file mode 100644 index 0000000..cca7e5a --- /dev/null +++ b/ch03/usingTime.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + fmt.Println("Epoch time:", time.Now().Unix()) + t := time.Now() + fmt.Println(t, t.Format(time.RFC3339)) + fmt.Println(t.Weekday(), t.Day(), t.Month(), t.Year()) + + time.Sleep(time.Second) + t1 := time.Now() + fmt.Println("Time difference:", t1.Sub(t)) + + formatT := t.Format("01 January 2006") + fmt.Println(formatT) + loc, _ := time.LoadLocation("Europe/Paris") + londonTime := t.In(loc) + fmt.Println("Paris:", londonTime) +} diff --git a/ch04/calculatePi.go b/ch04/calculatePi.go new file mode 100644 index 0000000..bfd0e33 --- /dev/null +++ b/ch04/calculatePi.go @@ -0,0 +1,82 @@ +package main + +import ( + "fmt" + "math" + "math/big" + "os" + "strconv" +) + +var precision uint = 0 + +func Pi(accuracy uint) *big.Float { + k := 0 + pi := new(big.Float).SetPrec(precision).SetFloat64(0) + k1k2k3 := new(big.Float).SetPrec(precision).SetFloat64(0) + k4k5k6 := new(big.Float).SetPrec(precision).SetFloat64(0) + temp := new(big.Float).SetPrec(precision).SetFloat64(0) + minusOne := new(big.Float).SetPrec(precision).SetFloat64(-1) + total := new(big.Float).SetPrec(precision).SetFloat64(0) + + two2Six := math.Pow(2, 6) + two2SixBig := new(big.Float).SetPrec(precision).SetFloat64(two2Six) + + for { + if k > int(accuracy) { + break + } + t1 := float64(float64(1) / float64(10*k+9)) + k1 := new(big.Float).SetPrec(precision).SetFloat64(t1) + t2 := float64(float64(64) / float64(10*k+3)) + k2 := new(big.Float).SetPrec(precision).SetFloat64(t2) + t3 := float64(float64(32) / float64(4*k+1)) + k3 := new(big.Float).SetPrec(precision).SetFloat64(t3) + k1k2k3.Sub(k1, k2) + k1k2k3.Sub(k1k2k3, k3) + + t4 := float64(float64(4) / float64(10*k+5)) + k4 := new(big.Float).SetPrec(precision).SetFloat64(t4) + t5 := float64(float64(4) / float64(10*k+7)) + k5 := new(big.Float).SetPrec(precision).SetFloat64(t5) + t6 := float64(float64(1) / float64(4*k+3)) + k6 := new(big.Float).SetPrec(precision).SetFloat64(t6) + k4k5k6.Add(k4, k5) + k4k5k6.Add(k4k5k6, k6) + k4k5k6 = k4k5k6.Mul(k4k5k6, minusOne) + temp.Add(k1k2k3, k4k5k6) + + k7temp := new(big.Int).Exp(big.NewInt(-1), big.NewInt(int64(k)), nil) + k8temp := new(big.Int).Exp(big.NewInt(1024), big.NewInt(int64(k)), nil) + + k7 := new(big.Float).SetPrec(precision).SetFloat64(0) + k7.SetInt(k7temp) + k8 := new(big.Float).SetPrec(precision).SetFloat64(0) + k8.SetInt(k8temp) + + t9 := float64(256) / float64(10*k+1) + k9 := new(big.Float).SetPrec(precision).SetFloat64(t9) + k9.Add(k9, temp) + total.Mul(k9, k7) + total.Quo(total, k8) + pi.Add(pi, total) + + k = k + 1 + } + pi.Quo(pi, two2SixBig) + return pi +} + +func main() { + arguments := os.Args + if len(arguments) == 1 { + fmt.Println("Please provide one numeric argument!") + os.Exit(1) + } + + temp, _ := strconv.ParseUint(arguments[1], 10, 32) + precision = uint(temp) * 3 + + PI := Pi(precision) + fmt.Println(PI) +} diff --git a/ch04/changeDT.go b/ch04/changeDT.go new file mode 100644 index 0000000..719fdba --- /dev/null +++ b/ch04/changeDT.go @@ -0,0 +1,66 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "os" + "regexp" + "strings" + "time" +) + +func main() { + + arguments := os.Args + if len(arguments) == 1 { + fmt.Println("Please provide one text file to process!") + os.Exit(1) + } + + filename := arguments[1] + f, err := os.Open(filename) + if err != nil { + fmt.Printf("error opening file %s", err) + os.Exit(1) + } + defer f.Close() + + notAMatch := 0 + r := bufio.NewReader(f) + for { + line, err := r.ReadString('\n') + if err == io.EOF { + break + } else if err != nil { + fmt.Printf("error reading file %s", err) + } + + r1 := regexp.MustCompile(`.*\[(\d\d\/\w+/\d\d\d\d:\d\d:\d\d:\d\d.*)\] .*`) + if r1.MatchString(line) { + match := r1.FindStringSubmatch(line) + d1, err := time.Parse("02/Jan/2006:15:04:05 -0700", match[1]) + if err == nil { + newFormat := d1.Format(time.Stamp) + fmt.Print(strings.Replace(line, match[1], newFormat, 1)) + } else { + notAMatch++ + } + continue + } + + r2 := regexp.MustCompile(`.*\[(\w+\-\d\d-\d\d:\d\d:\d\d:\d\d.*)\] .*`) + if r2.MatchString(line) { + match := r2.FindStringSubmatch(line) + d1, err := time.Parse("Jan-02-06:15:04:05 -0700", match[1]) + if err == nil { + newFormat := d1.Format(time.Stamp) + fmt.Print(strings.Replace(line, match[1], newFormat, 1)) + } else { + notAMatch++ + } + continue + } + } + fmt.Println(notAMatch, "lines did not match!") +} diff --git a/ch04/findIPv4.go b/ch04/findIPv4.go new file mode 100644 index 0000000..7bc6d86 --- /dev/null +++ b/ch04/findIPv4.go @@ -0,0 +1,54 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "net" + "os" + "path/filepath" + "regexp" +) + +func findIP(input string) string { + partIP := "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])" + grammar := partIP + "\\." + partIP + "\\." + partIP + "\\." + partIP + matchMe := regexp.MustCompile(grammar) + return matchMe.FindString(input) +} + +func main() { + arguments := os.Args + if len(arguments) < 2 { + fmt.Printf("usage: %s logFile\n", filepath.Base(arguments[0])) + os.Exit(1) + } + + for _, filename := range arguments[1:] { + f, err := os.Open(filename) + if err != nil { + fmt.Printf("error opening file %s\n", err) + os.Exit(-1) + } + defer f.Close() + + r := bufio.NewReader(f) + for { + line, err := r.ReadString('\n') + if err == io.EOF { + break + } else if err != nil { + fmt.Printf("error reading file %s", err) + break + } + + ip := findIP(line) + trial := net.ParseIP(ip) + if trial.To4() == nil { + continue + } else { + fmt.Println(ip) + } + } + } +} diff --git a/ch04/keyValue.go b/ch04/keyValue.go new file mode 100644 index 0000000..ef1eed5 --- /dev/null +++ b/ch04/keyValue.go @@ -0,0 +1,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!") + } + } +} diff --git a/ch04/logEntries.txt b/ch04/logEntries.txt new file mode 100644 index 0000000..225fb1b --- /dev/null +++ b/ch04/logEntries.txt @@ -0,0 +1,6 @@ +- - [21/Nov/2017:19:28:09 +0200] "GET /AMEv2.tif.zip HTTP/1.1" 200 2188249 "-" +- - [21/Jun/2017:19:28:09 +0200] "GET /AMEv2.tif.zip HTTP/1.1" 200 +- - [25/Lun/2017:20:05:34 +0200] "GET /MongoDjango.zip HTTP/1.1" 200 118362 +- - [Jun-21-17:19:28:09 +0200] "GET /AMEv2.tif.zip HTTP/1.1" 200 +- - [20/Nov/2017:20:05:34 +0200] "GET /MongoDjango.zip HTTP/1.1" 200 118362 +- - [35/Nov/2017:20:05:34 +0200] "GET MongoDjango.zip HTTP/1.1" 200 118362 diff --git a/ch04/pointerStruct.go b/ch04/pointerStruct.go new file mode 100644 index 0000000..a8fe311 --- /dev/null +++ b/ch04/pointerStruct.go @@ -0,0 +1,34 @@ +package main + +import ( + "fmt" +) + +type myStructure struct { + Name string + Surname string + Height int32 +} + +func createStruct(n, s string, h int32) *myStructure { + if h > 300 { + h = 0 + } + return &myStructure{n, s, h} +} + +func retStructure(n, s string, h int32) myStructure { + if h > 300 { + h = 0 + } + return myStructure{n, s, h} +} + +func main() { + s1 := createStruct("Mihalis", "Tsoukalos", 123) + s2 := retStructure("Mihalis", "Tsoukalos", 123) + fmt.Println((*s1).Name) + fmt.Println(s2.Name) + fmt.Println(s1) + fmt.Println(s2) +} diff --git a/ch04/runes.go b/ch04/runes.go new file mode 100644 index 0000000..174134d --- /dev/null +++ b/ch04/runes.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" +) + +func main() { + const r1 = '€' + fmt.Println("(int32) r1:", r1) + fmt.Printf("(HEX) r1: %x\n", r1) + fmt.Printf("(as a String) r1: %s\n", r1) + fmt.Printf("(as a character) r1: %c\n", r1) + + fmt.Println("A string is a collection of runes:", []byte("Mihalis")) + aString := []byte("Mihalis") + for x, y := range aString { + fmt.Println(x, y) + fmt.Printf("Char: %c\n", aString[x]) + } + fmt.Printf("%s\n", aString) +} diff --git a/ch04/selectColumn.go b/ch04/selectColumn.go new file mode 100644 index 0000000..263dda8 --- /dev/null +++ b/ch04/selectColumn.go @@ -0,0 +1,56 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "os" + "strconv" + "strings" +) + +func main() { + arguments := os.Args + if len(arguments) < 2 { + fmt.Printf("usage: selectColumn column [ [... = column { + fmt.Println((data[column-1])) + } + } + } +} diff --git a/ch04/strings.go b/ch04/strings.go new file mode 100644 index 0000000..6fe9353 --- /dev/null +++ b/ch04/strings.go @@ -0,0 +1,42 @@ +package main + +import ( + "fmt" +) + +func main() { + const sLiteral = "\x99\x42\x32\x55\x50\x35\x23\x50\x29\x9c" + fmt.Println(sLiteral) + fmt.Printf("x: %x\n", sLiteral) + + fmt.Printf("sLiteral length: %d\n", len(sLiteral)) + + for i := 0; i < len(sLiteral); i++ { + fmt.Printf("%x ", sLiteral[i]) + } + fmt.Println() + + fmt.Printf("q: %q\n", sLiteral) + fmt.Printf("+q: %+q\n", sLiteral) + fmt.Printf(" x: % x\n", sLiteral) + + fmt.Printf("s: As a string: %s\n", sLiteral) + + s2 := "€£³" + for x, y := range s2 { + fmt.Printf("%#U starts at byte position %d\n", y, x) + } + + fmt.Printf("s2 length: %d\n", len(s2)) + + const s3 = "ab12AB" + fmt.Println("s3:", s3) + fmt.Printf("x: % x\n", s3) + + fmt.Printf("s3 length: %d\n", len(s3)) + + for i := 0; i < len(s3); i++ { + fmt.Printf("%x ", s3[i]) + } + fmt.Println() +} diff --git a/ch04/structures.go b/ch04/structures.go new file mode 100644 index 0000000..3b2c11c --- /dev/null +++ b/ch04/structures.go @@ -0,0 +1,29 @@ +package main + +import ( + "fmt" +) + +func main() { + + type XYZ struct { + X int + Y int + Z int + } + + var s1 XYZ + fmt.Println(s1.Y, s1.Z) + + p1 := XYZ{23, 12, -2} + p2 := XYZ{Z: 12, Y: 13} + fmt.Println(p1) + fmt.Println(p2) + + pSlice := [4]XYZ{} + pSlice[2] = p1 + pSlice[0] = p2 + fmt.Println(pSlice) + p2 = XYZ{1, 2, 3} + fmt.Println(pSlice) +} diff --git a/ch04/switch.go b/ch04/switch.go new file mode 100644 index 0000000..d061710 --- /dev/null +++ b/ch04/switch.go @@ -0,0 +1,65 @@ +package main + +import ( + "fmt" + "os" + "regexp" + "strconv" +) + +func main() { + + arguments := os.Args + if len(arguments) < 2 { + fmt.Println("usage: switch number.") + os.Exit(1) + } + + number, err := strconv.Atoi(arguments[1]) + if err != nil { + fmt.Println("This value is not an integer:", number) + } else { + switch { + case number < 0: + fmt.Println("Less than zero!") + case number > 0: + fmt.Println("Bigger than zero!") + default: + fmt.Println("Zero!") + } + } + + asString := arguments[1] + switch asString { + case "5": + fmt.Println("Five!") + case "0": + fmt.Println("Zero!") + default: + fmt.Println("Do not care!") + } + + var negative = regexp.MustCompile(`-`) + var floatingPoint = regexp.MustCompile(`\d?\.\d`) + var email = regexp.MustCompile(`^[^@]+@[^@.]+\.[^@.]+`) + + switch { + case negative.MatchString(asString): + fmt.Println("Negative number") + case floatingPoint.MatchString(asString): + fmt.Println("Floating point!") + case email.MatchString(asString): + fmt.Println("It is an email!") + fallthrough + default: + fmt.Println("Something else!") + } + + var aType error = nil + switch aType.(type) { + case nil: + fmt.Println("It is nil interface!") + default: + fmt.Println("Not nil interface!") + } +} diff --git a/ch04/tuples.go b/ch04/tuples.go new file mode 100644 index 0000000..0c6a715 --- /dev/null +++ b/ch04/tuples.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" +) + +func retThree(x int) (int, int, int) { + return 2 * x, x * x, -x +} + +func main() { + fmt.Println(retThree(10)) + n1, n2, n3 := retThree(20) + fmt.Println(n1, n2, n3) + + n1, n2 = n2, n1 + fmt.Println(n1, n2, n3) + + x1, x2, x3 := n1*2, n1*n1, -n1 + fmt.Println(x1, x2, x3) +} diff --git a/ch04/unicode.go b/ch04/unicode.go new file mode 100644 index 0000000..ca53b6a --- /dev/null +++ b/ch04/unicode.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + "unicode" +) + +func main() { + const sL = "\x99\x00ab\x50\x00\x23\x50\x29\x9c" + + for i := 0; i < len(sL); i++ { + if unicode.IsPrint(rune(sL[i])) { + fmt.Printf("%c\n", sL[i]) + } else { + fmt.Println("Not printable!") + } + } +} diff --git a/ch04/useStrings.go b/ch04/useStrings.go new file mode 100644 index 0000000..3c157a4 --- /dev/null +++ b/ch04/useStrings.go @@ -0,0 +1,57 @@ +package main + +import ( + "fmt" + s "strings" + "unicode" +) + +var f = fmt.Printf + +func main() { + upper := s.ToUpper("Hello there!") + f("To Upper: %s\n", upper) + f("To Lower: %s\n", s.ToLower("Hello THERE")) + + f("%s\n", s.Title("tHis wiLL be A title!")) + + f("EqualFold: %v\n", s.EqualFold("Mihalis", "MIHAlis")) + f("EqualFold: %v\n", s.EqualFold("Mihalis", "MIHAli")) + + f("Prefix: %v\n", s.HasPrefix("Mihalis", "Mi")) + f("Prefix: %v\n", s.HasPrefix("Mihalis", "mi")) + f("Suffix: %v\n", s.HasSuffix("Mihalis", "is")) + f("Suffix: %v\n", s.HasSuffix("Mihalis", "IS")) + + f("Index: %v\n", s.Index("Mihalis", "ha")) + f("Index: %v\n", s.Index("Mihalis", "Ha")) + f("Count: %v\n", s.Count("Mihalis", "i")) + f("Count: %v\n", s.Count("Mihalis", "I")) + f("Repeat: %s\n", s.Repeat("ab", 5)) + + f("TrimSpace: %s\n", s.TrimSpace(" \tThis is a line. \n")) + f("TrimLeft: %s", s.TrimLeft(" \tThis is a\t line. \n", "\n\t ")) + f("TrimRight: %s\n", s.TrimRight(" \tThis is a\t line. \n", "\n\t ")) + + f("Compare: %v\n", s.Compare("Mihalis", "MIHALIS")) + f("Compare: %v\n", s.Compare("Mihalis", "Mihalis")) + f("Compare: %v\n", s.Compare("MIHALIS", "MIHalis")) + + f("Fields: %v\n", s.Fields("This is a string!")) + f("Fields: %v\n", s.Fields("Thisis\na\tstring!")) + + f("%s\n", s.Split("abcd efg", "")) + f("%s\n", s.Replace("abcd efg", "", "_", -1)) + f("%s\n", s.Replace("abcd efg", "", "_", 4)) + f("%s\n", s.Replace("abcd efg", "", "_", 2)) + + lines := []string{"Line 1", "Line 2", "Line 3"} + f("Join: %s\n", s.Join(lines, "+++")) + + f("SplitAfter: %s\n", s.SplitAfter("123++432++", "++")) + + trimFunction := func(c rune) bool { + return !unicode.IsLetter(c) + } + f("TrimFunc: %s\n", s.TrimFunc("123 abc ABC \t .", trimFunction)) +}