ch03 + ch04

This commit is contained in:
Mihalis Tsoukalos 2019-01-10 22:08:08 +02:00
commit a39cfd0b05
29 changed files with 1157 additions and 0 deletions

54
ch03/constants.go Normal file
View file

@ -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)
}

41
ch03/copySlice.go Normal file
View file

@ -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)
}

14
ch03/failMap.go Normal file
View file

@ -0,0 +1,14 @@
package main
import (
"fmt"
)
func main() {
aMap := map[string]int{}
aMap = nil
fmt.Println(aMap)
aMap["test"] = 1
}

30
ch03/lenCap.go Normal file
View file

@ -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))
}

48
ch03/loops.go Normal file
View file

@ -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)
}
}

26
ch03/parseDate.go Normal file
View file

@ -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)
}
}

25
ch03/parseTime.go Normal file
View file

@ -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)
}
}

38
ch03/pointers.go Normal file
View file

@ -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)
}

17
ch03/reslice.go Normal file
View file

@ -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)
}

41
ch03/slices.go Normal file
View file

@ -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()
}
}

32
ch03/sortSlice.go Normal file
View file

@ -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)
}

34
ch03/timeDate.go Normal file
View file

@ -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!")
}
}
}

35
ch03/usingArrays.go Normal file
View file

@ -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()
}
}

35
ch03/usingMaps.go Normal file
View file

@ -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)
}
}

23
ch03/usingTime.go Normal file
View file

@ -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)
}

82
ch04/calculatePi.go Normal file
View file

@ -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)
}

66
ch04/changeDT.go Normal file
View file

@ -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!")
}

54
ch04/findIPv4.go Normal file
View file

@ -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)
}
}
}
}

113
ch04/keyValue.go Normal file
View file

@ -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!")
}
}
}

6
ch04/logEntries.txt Normal file
View file

@ -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

34
ch04/pointerStruct.go Normal file
View file

@ -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)
}

21
ch04/runes.go Normal file
View file

@ -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)
}

56
ch04/selectColumn.go Normal file
View file

@ -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 <file1> [<file2> [... <fileN]]\n")
os.Exit(1)
}
temp, err := strconv.Atoi(arguments[1])
if err != nil {
fmt.Println("Column value is not an integer:", temp)
return
}
column := temp
if column < 0 {
fmt.Println("Invalid Column number!")
os.Exit(1)
}
for _, filename := range arguments[2:] {
fmt.Println("\t\t", filename)
f, err := os.Open(filename)
if err != nil {
fmt.Printf("error opening file %s\n", err)
continue
}
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)
}
data := strings.Fields(line)
if len(data) >= column {
fmt.Println((data[column-1]))
}
}
}
}

42
ch04/strings.go Normal file
View file

@ -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()
}

29
ch04/structures.go Normal file
View file

@ -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)
}

65
ch04/switch.go Normal file
View file

@ -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!")
}
}

21
ch04/tuples.go Normal file
View file

@ -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)
}

18
ch04/unicode.go Normal file
View file

@ -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!")
}
}
}

57
ch04/useStrings.go Normal file
View file

@ -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))
}