diff --git a/LectureCodeExamples/arrays_slices_and_maps/01-arrays/example_01/main.go b/LectureCodeExamples/arrays_slices_and_maps/01-arrays/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..f7d5256182b2bc0cabc1de0d2f52557d7799cd27 --- /dev/null +++ b/LectureCodeExamples/arrays_slices_and_maps/01-arrays/example_01/main.go @@ -0,0 +1,16 @@ +package main + +import "fmt" + +func main() { + + var a[5] int + fmt.Println(a) + + b := [5]int{0,1,2,3,4} + fmt.Println(b) + + c := [5]int{0,1,2} + fmt.Println(c) + +} diff --git a/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_01/main.go b/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..ddfb7627c232afe39e0abadf85842ac3b56c9f5a --- /dev/null +++ b/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_01/main.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" +) + +func main(){ + a := [5]string{"a","b","c","d","e"} + + fmt.Println(a) + fmt.Println(a[:]) + fmt.Println(a[0]) + fmt.Println(a[0],a[1],a[2],a[3],a[4]) + fmt.Println(a[0:2]) + fmt.Println(a[1:4]) + fmt.Println(a[:2]) + fmt.Println(a[2:]) +} diff --git a/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_02/main.go b/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..bda75b320e764db74565fbf4f7620318a435ed34 --- /dev/null +++ b/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_02/main.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + "reflect" +) + +func main() { + a := [5]string{"a","b","c","d","e"} + + fmt.Println(reflect.TypeOf(a)) + fmt.Println(reflect.TypeOf(a[0:3])) + fmt.Println(reflect.TypeOf(a[0])) +} diff --git a/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_03/main.go b/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_03/main.go new file mode 100644 index 0000000000000000000000000000000000000000..3eeb203ea5e272206dc9890eb99caa71af231566 --- /dev/null +++ b/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_03/main.go @@ -0,0 +1,23 @@ +package main + +import "fmt" + +func main() { + + a := []int{0,1,2,3,4} + + fmt.Println(a, len(a), cap(a)) + + b := append(a,5) + fmt.Println(b, len(b), cap(b)) + b = append(b,6) + fmt.Println(b, len(b), cap(b)) + + c := b[1:4] + fmt.Println(c, len(c), cap(c)) + + d := make([]int,5,10) + fmt.Println(d, len(d), cap(d)) + // d[6]=5 --> This will fail + +} diff --git a/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_04/main.go b/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_04/main.go new file mode 100644 index 0000000000000000000000000000000000000000..9957e6ca86a4cd2e91492a22e6e3077e0ab95d48 --- /dev/null +++ b/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_04/main.go @@ -0,0 +1,17 @@ +package main + +import "fmt" + +func main(){ + names := []string{ + "Jeremy", "John", "Joseph", + } + + for i:=0;i<len(names);i++{ + fmt.Println(i,names[i]) + } + + for position, name := range(names){ + fmt.Println(position,name) + } +} diff --git a/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_05/main.go b/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_05/main.go new file mode 100644 index 0000000000000000000000000000000000000000..2e6e221f05dc8a3b320088e8677bad52a919db5f --- /dev/null +++ b/LectureCodeExamples/arrays_slices_and_maps/02-slices/example_05/main.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +func main(){ + names := []string{ + "Jeremy", "John", "Joseph", + } + + for _, name := range(names){ + name = name + "_changed" + } + fmt.Println(names) + + for position, name := range(names){ + names[position] = name + "_changed" + } + fmt.Println(names) + + +} diff --git a/LectureCodeExamples/arrays_slices_and_maps/03-maps/example_01/main.go b/LectureCodeExamples/arrays_slices_and_maps/03-maps/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..de4b0a3bc59568a3698624abddc2e8ed4e6c55a3 --- /dev/null +++ b/LectureCodeExamples/arrays_slices_and_maps/03-maps/example_01/main.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +func main() { + var ages map[string]int + fmt.Println(ages) + + // This fails, ages was not initialized + // ages["Jesus"] = 33 + + ages = make(map[string]int,5) + // Now it works because it was initialized + ages["Jesus"] = 33 + + ages = map[string]int{ + "Jesus": 33, + "Mathusalem": 969, + } + fmt.Println(ages) +} diff --git a/LectureCodeExamples/arrays_slices_and_maps/03-maps/example_02/main.go b/LectureCodeExamples/arrays_slices_and_maps/03-maps/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..84b0f46c6b5b9305685024db75d471f40787a4fa --- /dev/null +++ b/LectureCodeExamples/arrays_slices_and_maps/03-maps/example_02/main.go @@ -0,0 +1,24 @@ +package main + +import "fmt" + +func main() { + birthdays := map[string]string{ + "Jesus": "12-25-0000", + "Budha": "563 BEC", + } + fmt.Println(birthdays,len(birthdays)) + + xmas, found := birthdays["Jesus"] + fmt.Println(xmas, found) + + delete(birthdays, "Jesus") + fmt.Println(birthdays,len(birthdays)) + + _, found = birthdays["Jesus"] + fmt.Println("Did we find when its Xmas?", found) + + birthdays["Jesus"]="12-25-0000" + fmt.Println(birthdays) + +} diff --git a/LectureCodeExamples/arrays_slices_and_maps/03-maps/example_03/main.go b/LectureCodeExamples/arrays_slices_and_maps/03-maps/example_03/main.go new file mode 100644 index 0000000000000000000000000000000000000000..5c3e07edcf612662dbae2cf241712f1b4aeebe2d --- /dev/null +++ b/LectureCodeExamples/arrays_slices_and_maps/03-maps/example_03/main.go @@ -0,0 +1,17 @@ +package main + +import "fmt" + +func main(){ + sales := map[string]int { + "Jan": 34345, + "Feb": 11823, + "Mar": 8838, + "Apr": 33, + } + + fmt.Println("Month\tSales") + for month, sale := range sales { + fmt.Printf("%s\t%d\n",month,sale) + } +} diff --git a/LectureCodeExamples/basics/00-types/summary/main.go b/LectureCodeExamples/basics/00-types/summary/main.go new file mode 100644 index 0000000000000000000000000000000000000000..826f9942149724a2534168a4effb50b50609719c --- /dev/null +++ b/LectureCodeExamples/basics/00-types/summary/main.go @@ -0,0 +1,17 @@ +package main + +import "fmt" + +func main() { + var aBool bool = true + var aString string = "yXXXy" + var aComplex complex64 = 5i + var aRune rune = '€' + + fmt.Println(aBool) + fmt.Println(aString) + fmt.Println(aComplex) + fmt.Println(aRune) + fmt.Printf("%U\n",aRune) + fmt.Printf("%c\n",aRune) +} diff --git a/LectureCodeExamples/basics/01-variables/example_01/main.go b/LectureCodeExamples/basics/01-variables/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..859103ddce42121ef1950b682812b72a59cf598d --- /dev/null +++ b/LectureCodeExamples/basics/01-variables/example_01/main.go @@ -0,0 +1,30 @@ +package main + +import "fmt" + +func main() { + + var a int + a = 42 + + var aa int = 100 + + b := -42 + + c := "this is a string" + + var d, e string + d, e = "var d", "var e" + + f, g := true, false + + fmt.Println(a) + fmt.Println(aa) + fmt.Println(b) + fmt.Println(c) + fmt.Println(d) + fmt.Println(e) + fmt.Println(f) + fmt.Println(g) + +} diff --git a/LectureCodeExamples/basics/02-constants/main.go b/LectureCodeExamples/basics/02-constants/main.go new file mode 100644 index 0000000000000000000000000000000000000000..f66c7f38375b9cc6f2a13f09042b815aed407cea --- /dev/null +++ b/LectureCodeExamples/basics/02-constants/main.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" + "reflect" +) + +const ( + Pi = 3.14 + Avogadro float32 = 6.022e23 +) + + +func main() { + fmt.Println("What is the value of Pi? Pi is", Pi) + fmt.Println(reflect.TypeOf(Pi)) + fmt.Println("Avogadro's Number value is", Avogadro) + fmt.Println(reflect.TypeOf(Avogadro)) +} diff --git a/LectureCodeExamples/basics/03-enums/main.go b/LectureCodeExamples/basics/03-enums/main.go new file mode 100644 index 0000000000000000000000000000000000000000..c9909bee8a9bee5c655afa82b4369e8cf2fcef21 --- /dev/null +++ b/LectureCodeExamples/basics/03-enums/main.go @@ -0,0 +1,22 @@ +package main + +import "fmt" + +type DayOfTheWeek uint8 + +const( + Monday DayOfTheWeek = iota + Tuesday + Wednesday + Thursday + Friday + Saturday + Sunday +) + +func main() { + + fmt.Printf("Monday is %d\n", Monday) + fmt.Printf("Wednesday is %d\n", Wednesday) + fmt.Printf("Friday is %d\n", Friday) +} diff --git a/LectureCodeExamples/basics/04-functions/example_01/main.go b/LectureCodeExamples/basics/04-functions/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..e12d7789ac9cbddd0798a6f54955ac83d4585d86 --- /dev/null +++ b/LectureCodeExamples/basics/04-functions/example_01/main.go @@ -0,0 +1,12 @@ +package main + +import "fmt" + +func sum(a int, b int) int { + return a + b +} + +func main() { + result := sum(2,2) + fmt.Println(result) +} diff --git a/LectureCodeExamples/basics/04-functions/example_02/main.go b/LectureCodeExamples/basics/04-functions/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..3f7b8091ff789b6f792df5a0116fa025df38505f --- /dev/null +++ b/LectureCodeExamples/basics/04-functions/example_02/main.go @@ -0,0 +1,14 @@ +package main + +import "fmt" + +func ops(a int, b int) (int, int) { + return a + b, a - b +} + +func main() { + sum, subs := ops(2,2) + fmt.Println("2+2=",sum, "2-2=",subs) + b, _ := ops(10,2) + fmt.Println("10+2=",b) +} diff --git a/LectureCodeExamples/basics/04-functions/example_03/main.go b/LectureCodeExamples/basics/04-functions/example_03/main.go new file mode 100644 index 0000000000000000000000000000000000000000..fbdfbd550e8e66cf969f347cb059cd19a033baf3 --- /dev/null +++ b/LectureCodeExamples/basics/04-functions/example_03/main.go @@ -0,0 +1,16 @@ +package main + +import "fmt" + +func sum(nums ...int) int { + total := 0 + for _, a := range(nums) { + total = total + a + } + return total +} + +func main(){ + total := sum(1,2,3,4,5) + fmt.Println("The first five numbers sum is",total) +} diff --git a/LectureCodeExamples/basics/04-functions/example_04/main.go b/LectureCodeExamples/basics/04-functions/example_04/main.go new file mode 100644 index 0000000000000000000000000000000000000000..3c4d4d7cec84bd60f23e15ea8fe9eb68c586fa70 --- /dev/null +++ b/LectureCodeExamples/basics/04-functions/example_04/main.go @@ -0,0 +1,22 @@ +package main + +import "fmt" + +func doit(operator func(int,int) int, a int, b int) int { + return operator(a,b) +} + +func sum(a int, b int) int { + return a + b +} + +func multiply(a int, b int) int { + return a * b +} + +func main() { + c := doit(sum, 2, 3) + fmt.Println("2+3=", c) + d := doit(multiply, 2, 3) + fmt.Println("2*3=", d) +} diff --git a/LectureCodeExamples/basics/04-functions/example_05/main.go b/LectureCodeExamples/basics/04-functions/example_05/main.go new file mode 100644 index 0000000000000000000000000000000000000000..57d5f938bde4959bdfd6972da9e7fd16107d9227 --- /dev/null +++ b/LectureCodeExamples/basics/04-functions/example_05/main.go @@ -0,0 +1,22 @@ +package main + +import "fmt" + +func accumulator(increment int) func() int { + i:=0 + return func() int { + i = i + increment + return i + } +} + +func main() { + + a := accumulator(1) + b := accumulator(2) + + fmt.Println("a","b") + for i:=0;i<5;i++ { + fmt.Println(a(),b()) + } +} diff --git a/LectureCodeExamples/basics/05-pointers/example_01/main.go b/LectureCodeExamples/basics/05-pointers/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..59911d3efa45ebf9f3f8b082080ae4ebf3819ffc --- /dev/null +++ b/LectureCodeExamples/basics/05-pointers/example_01/main.go @@ -0,0 +1,22 @@ +package main + +import "fmt" + +func a (i int){ + i = 0 +} + +func b (i *int) { + *i = 0 +} + +func main() { + x := 100 + + a(x) + fmt.Println(x) + b(&x) + fmt.Println(x) + + fmt.Println(&x) +} diff --git a/LectureCodeExamples/basics/06-nil_zero_values/example_01/main.go b/LectureCodeExamples/basics/06-nil_zero_values/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..5de0212ba1ed508d5a2cc78f851b0c8d97221b11 --- /dev/null +++ b/LectureCodeExamples/basics/06-nil_zero_values/example_01/main.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +func main() { + + var a int + fmt.Println(a) + + var b *int + fmt.Println(b) + + var c bool + fmt.Println(c) + + var d func() + fmt.Println(d) + + var e string + fmt.Printf("[%s]",e) +} diff --git a/LectureCodeExamples/basics/07-controlFlow/for/main.go b/LectureCodeExamples/basics/07-controlFlow/for/main.go new file mode 100644 index 0000000000000000000000000000000000000000..4ae28b71813af3fa1aa75cb61d3cb09e1a85b551 --- /dev/null +++ b/LectureCodeExamples/basics/07-controlFlow/for/main.go @@ -0,0 +1,38 @@ +package main + +import ( + "fmt" + +) + +func main() { + + x := 5 + + counter := x + + for counter > 0 { + fmt.Println(counter) + counter-- + } + + for i:=0; i < x; i++ { + fmt.Print(i) + } + fmt.Println() + + for { + if x % 2 != 0 { + fmt.Printf("%d is odd\n", x) + x++ + continue + } + break + } + + for { + fmt.Println("Never stop") + break + } + +} diff --git a/LectureCodeExamples/basics/07-controlFlow/ifConditional/main.go b/LectureCodeExamples/basics/07-controlFlow/ifConditional/main.go new file mode 100644 index 0000000000000000000000000000000000000000..2dff628e03a44ac17f06d390b07be6ac3958796c --- /dev/null +++ b/LectureCodeExamples/basics/07-controlFlow/ifConditional/main.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + "math/rand" + "time" +) + +func main() { + rand.Seed(time.Now().UnixNano()) + x := rand.Float32() + + if x < 0.5 { + fmt.Println("head") + } else { + fmt.Println("tail") + } +} diff --git a/LectureCodeExamples/basics/07-controlFlow/switch/example01/main.go b/LectureCodeExamples/basics/07-controlFlow/switch/example01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..89d52344ec3c3402d263d381902195881f37e579 --- /dev/null +++ b/LectureCodeExamples/basics/07-controlFlow/switch/example01/main.go @@ -0,0 +1,22 @@ +package main + +import "fmt" + +func main() { + var finger int = 1 + + switch finger { + case 0: + fmt.Println("Thumb") + case 1: + fmt.Println("Index") + case 2: + fmt.Println("Middle") + case 3: + fmt.Println("Ring") + case 4: + fmt.Println("Pinkie") + default: + fmt.Println("Humans usually have no more than five fingers") + } +} diff --git a/LectureCodeExamples/basics/07-controlFlow/switch/example02/main.go b/LectureCodeExamples/basics/07-controlFlow/switch/example02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..6e494f60f8a8f352227f4c0eda5ff50b79ab3e1f --- /dev/null +++ b/LectureCodeExamples/basics/07-controlFlow/switch/example02/main.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "math/rand" + "time" +) + +func main() { + + rand.Seed(time.Now().UnixNano()) + x := rand.Float32() + + switch { + case x < 0.25: + fmt.Println("Q1") + case x < 0.5: + fmt.Println("Q2") + case x < 0.75: + fmt.Println("Q3") + default: + fmt.Println("Q4") + } +} diff --git a/LectureCodeExamples/basics/08-errors/example_01/main.go b/LectureCodeExamples/basics/08-errors/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..3e37c55dd3c64beebedbe8d83b03fd61a767f91b --- /dev/null +++ b/LectureCodeExamples/basics/08-errors/example_01/main.go @@ -0,0 +1,32 @@ +package main + +import ( + "errors" + "fmt" + "math/rand" + "time" +) + +var Musketeers = []string{ + "Athos", "Porthos", "Aramis", "D'Artagnan", +} + +func GetMusketeer(id int) (string, error){ + if id < 0 || id >= len(Musketeers) { + return "", errors.New( + fmt.Sprintf("Invalid id [%d]",id)) + } + return Musketeers[id], nil +} + +func main() { + rand.Seed(time.Now().UnixNano()) + id := rand.Int() % 6 + + mosq, err := GetMusketeer(id) + if err == nil { + fmt.Printf("[%d] %s",id, mosq) + } else { + fmt.Println(err) + } +} diff --git a/LectureCodeExamples/basics/09-defer_panic_recover/example_01/main.go b/LectureCodeExamples/basics/09-defer_panic_recover/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..1e856d7eeb887dda7ac79a8c040826363b4adba0 --- /dev/null +++ b/LectureCodeExamples/basics/09-defer_panic_recover/example_01/main.go @@ -0,0 +1,16 @@ +package main + +import "fmt" + +func CloseMsg() { + fmt.Println("Closed!!!") +} + +func main() { + defer CloseMsg() + + fmt.Println("Doing something...") + defer fmt.Println("Certainly closed!!!") + fmt.Println("Doing something else...") + +} diff --git a/LectureCodeExamples/basics/09-defer_panic_recover/example_02/main.go b/LectureCodeExamples/basics/09-defer_panic_recover/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..2634dfd161d58dcaba16a5312da5cb58402b96df --- /dev/null +++ b/LectureCodeExamples/basics/09-defer_panic_recover/example_02/main.go @@ -0,0 +1,19 @@ +package main + +import "fmt" + +func something() { + defer fmt.Println("closed something") + for i:=0;i<5;i++ { + fmt.Println(i) + if i > 2 { + panic("Panic was called") + } + } +} + +func main () { + defer fmt.Println("closed main") + something() + fmt.Println("Something was finished") +} diff --git a/LectureCodeExamples/basics/09-defer_panic_recover/example_03/main.go b/LectureCodeExamples/basics/09-defer_panic_recover/example_03/main.go new file mode 100644 index 0000000000000000000000000000000000000000..f1f6289954c5a945506faa950e14fd78a56e6f15 --- /dev/null +++ b/LectureCodeExamples/basics/09-defer_panic_recover/example_03/main.go @@ -0,0 +1,26 @@ +package main + +import "fmt" + +func something() { + defer func() { + r := recover() + if r != nil{ + fmt.Println("No need to panic if i=",r) + } + }() + for i:=0;i<5;i++ { + fmt.Println(i) + if i > 2 { + panic(i) + } + } + fmt.Println("Closed something normally") +} + +func main () { + defer fmt.Println("closed main") + + something() + fmt.Println("Main was finished") +} diff --git a/LectureCodeExamples/basics/10-init_functions/example_01/main.go b/LectureCodeExamples/basics/10-init_functions/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..9d3e48a86788718c015799e742a8b83d73dcd22f --- /dev/null +++ b/LectureCodeExamples/basics/10-init_functions/example_01/main.go @@ -0,0 +1,18 @@ +package main + +import "fmt" + +var x = xSetter() + +func xSetter() int{ + fmt.Println("xSetter") + return 42 +} + +func init() { + fmt.Println("Init function") +} + +func main() { + fmt.Println("This is the main") +} diff --git a/LectureCodeExamples/basics/10-init_functions/example_02/a/a.go b/LectureCodeExamples/basics/10-init_functions/example_02/a/a.go new file mode 100644 index 0000000000000000000000000000000000000000..346e7cd379f5dab66c19d730d795bddbf04fcca6 --- /dev/null +++ b/LectureCodeExamples/basics/10-init_functions/example_02/a/a.go @@ -0,0 +1,11 @@ +package a + +import "fmt" + +func init() { + fmt.Println("Init 1 from package a") +} + +func init() { + fmt.Println("Init 2 from package a") +} diff --git a/LectureCodeExamples/basics/10-init_functions/example_02/go.mod b/LectureCodeExamples/basics/10-init_functions/example_02/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..7e30665c28fb374c1dff5f08f1a43adec95ade3a --- /dev/null +++ b/LectureCodeExamples/basics/10-init_functions/example_02/go.mod @@ -0,0 +1,3 @@ +module github.com/arasevic/savetheworldwithgo/02_the_basics/init_functions/example_02 + +go 1.14 diff --git a/LectureCodeExamples/basics/10-init_functions/example_02/main b/LectureCodeExamples/basics/10-init_functions/example_02/main new file mode 100644 index 0000000000000000000000000000000000000000..180906e68d470b5cd9049da329003de2d4af26e5 Binary files /dev/null and b/LectureCodeExamples/basics/10-init_functions/example_02/main differ diff --git a/LectureCodeExamples/basics/10-init_functions/example_02/main.go b/LectureCodeExamples/basics/10-init_functions/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..f18fccd328c06444e0e6ac9c5a3ff6a602c131a0 --- /dev/null +++ b/LectureCodeExamples/basics/10-init_functions/example_02/main.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + _ "github.com/arasevic/savetheworldwithgo/02_the_basics/init_functions/example_02/a" +) + +func init() { + fmt.Println("Init from my program") +} + +func main() { + fmt.Println("My program") +} diff --git a/LectureCodeExamples/concurrency/atomics/example_01/main.go b/LectureCodeExamples/concurrency/atomics/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..c8ffbd49dbfeff9dbcfb5ec06e26ddce1f1042a4 --- /dev/null +++ b/LectureCodeExamples/concurrency/atomics/example_01/main.go @@ -0,0 +1,34 @@ +package main + +import ( + "fmt" + "sync/atomic" + "time" +) + +func increaser(counter *int32) { + for { + atomic.AddInt32(counter,2) + time.Sleep(time.Millisecond*500) + } +} + +func decreaser(counter *int32) { + for { + atomic.AddInt32(counter, -1) + time.Sleep(time.Millisecond*250) + } +} + +func main() { + var counter int32 = 0 + + go increaser(&counter) + go decreaser(&counter) + + for i:=0;i<5;i++{ + time.Sleep(time.Millisecond*500) + fmt.Println(atomic.LoadInt32(&counter)) + } + fmt.Println(atomic.LoadInt32(&counter)) +} diff --git a/LectureCodeExamples/concurrency/atomics/example_02/main.go b/LectureCodeExamples/concurrency/atomics/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..c4d9605703fe1b0e9d03b26084d84e938540fe8d --- /dev/null +++ b/LectureCodeExamples/concurrency/atomics/example_02/main.go @@ -0,0 +1,44 @@ +package main + +import ( + "fmt" + "sync" + "sync/atomic" + "time" +) + +type Monitor struct { + ActiveUsers int + Requests int +} + +func updater(monitor atomic.Value, m *sync.Mutex) { + for { + time.Sleep(time.Millisecond*500) + m.Lock() + current := monitor.Load().(*Monitor) + current.ActiveUsers += 100 + current.Requests += 300 + monitor.Store(current) + m.Unlock() + } +} + +func observe(monitor atomic.Value) { + for { + time.Sleep(time.Second) + current := monitor.Load() + fmt.Printf("%v\n", current) + } +} + +func main() { + var monitor atomic.Value + monitor.Store(&Monitor{0,0}) + m := sync.Mutex{} + + go updater(monitor, &m) + go observe(monitor) + + time.Sleep(time.Second * 5) +} diff --git a/LectureCodeExamples/concurrency/channels/example_01/main.go b/LectureCodeExamples/concurrency/channels/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..562a22b384507820df1b1ba248dab69bad118d91 --- /dev/null +++ b/LectureCodeExamples/concurrency/channels/example_01/main.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "time" +) + +func generator(ch chan int) { + sum := 0 + for i:=0;i<5;i++ { + time.Sleep(time.Millisecond * 500) + sum = sum + i + } + ch <- sum +} + +func main() { + + ch := make(chan int) + + go generator(ch) + + fmt.Println("main waits for result...") + result := <- ch + + fmt.Println(result) +} diff --git a/LectureCodeExamples/concurrency/channels/example_01a/main.go b/LectureCodeExamples/concurrency/channels/example_01a/main.go new file mode 100644 index 0000000000000000000000000000000000000000..be3d531851621b3bbd30b6e7d0cbe0465c9d421b --- /dev/null +++ b/LectureCodeExamples/concurrency/channels/example_01a/main.go @@ -0,0 +1,31 @@ +package main + +import ( + "fmt" + "time" +) + +func generator(ch chan int) { + fmt.Println("generator waits for n") + n := <- ch + fmt.Println("n is",n) + sum := 0 + for i:=0;i<n;i++ { + sum = sum + i + } + ch <- sum +} + +func main() { + + ch := make(chan int) + + go generator(ch) + + fmt.Println("main waits for result...") + time.Sleep(time.Second) + ch <- 5 + result := <- ch + + fmt.Println(result) +} diff --git a/LectureCodeExamples/concurrency/channels/example_02/main.go b/LectureCodeExamples/concurrency/channels/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..b1217541baac8dc8b4962bdbebd918e73c3b8752 --- /dev/null +++ b/LectureCodeExamples/concurrency/channels/example_02/main.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + "time" +) + +func MrA(ch chan string) { + time.Sleep(time.Millisecond*500) + ch <- "This is MrA" +} + +func MrB(ch chan string) { + time.Sleep(time.Millisecond*200) + ch <- "This is MrB" +} + +func main() { + //ch := make(chan string) + ch := make(chan string,1) + + ch <- "This is main" + + go MrA(ch) + go MrB(ch) + + fmt.Println(<-ch) + fmt.Println(<-ch) + fmt.Println(<-ch) +} diff --git a/LectureCodeExamples/concurrency/channels/example_03/main.go b/LectureCodeExamples/concurrency/channels/example_03/main.go new file mode 100644 index 0000000000000000000000000000000000000000..5ca2b17efaed0990ac0159e0e6b8bdfa4307b135 --- /dev/null +++ b/LectureCodeExamples/concurrency/channels/example_03/main.go @@ -0,0 +1,32 @@ +package main + +import ( + "fmt" + "time" +) + +func sender(out chan int) { + for i:=0;i<5;i++ { + time.Sleep(time.Millisecond * 500) + out <- i + } + close(out) + fmt.Println("sender finished") +} + +func main() { + + ch := make(chan int) + + go sender(ch) + + for { + num, found := <- ch + if found { + fmt.Println(num) + } else { + fmt.Println("finished") + break + } + } +} diff --git a/LectureCodeExamples/concurrency/channels/example_04/main.go b/LectureCodeExamples/concurrency/channels/example_04/main.go new file mode 100644 index 0000000000000000000000000000000000000000..c739584ae1adc06aaffdd092c2ab2341bd0f7cd8 --- /dev/null +++ b/LectureCodeExamples/concurrency/channels/example_04/main.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +func generator(ch chan int) { + for i:=0;i<5;i++{ + ch <- i + } + close(ch) +} + +func main() { + ch := make(chan int) + + go generator(ch) + + for x := range(ch) { + fmt.Println(x) + } + fmt.Println("Done") +} diff --git a/LectureCodeExamples/concurrency/channels/example_05/main.go b/LectureCodeExamples/concurrency/channels/example_05/main.go new file mode 100644 index 0000000000000000000000000000000000000000..681cdcba5a4868a3341873308ee5d82edd48c5c7 --- /dev/null +++ b/LectureCodeExamples/concurrency/channels/example_05/main.go @@ -0,0 +1,32 @@ +package main + +import ( + "fmt" + "time" +) + +func receiver(input <- chan int) { + for i := range input { + fmt.Println(i) + } +} + +func sender(output chan <- int, n int) { + for i:=0;i<n;i++ { + time.Sleep(time.Millisecond * 500) + output <- i * i + } + close(output) +} + + +func main() { + + ch := make(chan int) + + go sender(ch, 4) + go receiver(ch) + + time.Sleep(time.Second*5) + fmt.Println("Done") +} diff --git a/LectureCodeExamples/concurrency/context/parents/main.go b/LectureCodeExamples/concurrency/context/parents/main.go new file mode 100644 index 0000000000000000000000000000000000000000..29e92bcf288ae64d4dd1bfe05960ed972489fcf7 --- /dev/null +++ b/LectureCodeExamples/concurrency/context/parents/main.go @@ -0,0 +1,40 @@ +package main + +import ( + "context" + "fmt" + "time" +) + +func calc(ctx context.Context) { + switch ctx.Value("action") { + case "quick": + fmt.Println("quick answer") + case "slow": + time.Sleep(time.Millisecond*500) + fmt.Println("slow answer") + case <- ctx.Done(): + fmt.Println("Done!!!") + default: + panic("unknown action") + } +} + +func main() { + t := time.Millisecond*300 + ctx, cancel := context.WithTimeout(context.Background(), t) + qCtx := context.WithValue(ctx, "action", "quick") + defer cancel() + + go calc(qCtx) + <-qCtx.Done() + + ctx2, cancel2 := context.WithTimeout(context.Background(), t) + sCtx := context.WithValue(ctx2, "action", "slow") + defer cancel2() + + go calc(sCtx) + <-sCtx.Done() + + fmt.Println("Finished") +} diff --git a/LectureCodeExamples/concurrency/context/with_cancel/main.go b/LectureCodeExamples/concurrency/context/with_cancel/main.go new file mode 100644 index 0000000000000000000000000000000000000000..3773d686eae22814eaa7bdfc61a53d99b1591225 --- /dev/null +++ b/LectureCodeExamples/concurrency/context/with_cancel/main.go @@ -0,0 +1,36 @@ +package main + +import ( + "context" + "fmt" + "sync/atomic" + "time" +) + +func setter(id int, c *int32, ctx context.Context) { + t := time.NewTicker(time.Millisecond*300) + for { + select { + case <- ctx.Done(): + fmt.Println("Done", id) + return + case <- t.C: + atomic.AddInt32(c, 1) + } + } +} + +func main() { + ctx, cancel := context.WithCancel(context.Background()) + + var c int32 = 0 + for i:=0;i<5;i++ { + go setter(i, &c, ctx) + } + + time.Sleep(time.Second * 1) + fmt.Println("Final check: ", c) + + cancel() + time.Sleep(time.Second) +} diff --git a/LectureCodeExamples/concurrency/context/with_deadline/main.go b/LectureCodeExamples/concurrency/context/with_deadline/main.go new file mode 100644 index 0000000000000000000000000000000000000000..73ee08f770962cbf220fef96ed75b7c89bb32c1f --- /dev/null +++ b/LectureCodeExamples/concurrency/context/with_deadline/main.go @@ -0,0 +1,36 @@ +package main + +import ( + "context" + "fmt" + "sync/atomic" + "time" +) + +func accum(c *uint32, ctx context.Context) { + t := time.NewTicker(time.Millisecond*250) + for { + select { + case <- t.C: + atomic.AddUint32(c, 1) + case <- ctx.Done(): + fmt.Println("Done context") + return + } + } +} + +func main() { + d := time.Now().Add(time.Second*3) + ctx, cancel := context.WithDeadline(context.Background(), d) + defer cancel() + + var counter uint32 = 0 + + for i:=0;i<5;i++ { + go accum(&counter, ctx) + } + + <- ctx.Done() + fmt.Println("counter is:", counter) +} diff --git a/LectureCodeExamples/concurrency/context/with_timeout/main.go b/LectureCodeExamples/concurrency/context/with_timeout/main.go new file mode 100644 index 0000000000000000000000000000000000000000..c129bdffbb4a41c3f00ad64449bc981341b01e40 --- /dev/null +++ b/LectureCodeExamples/concurrency/context/with_timeout/main.go @@ -0,0 +1,36 @@ +package main + +import ( + "context" + "fmt" + "time" +) + +func work(i int, info chan int) { + t := time.Duration(i*100)*time.Millisecond + time.Sleep(t) + info <- i +} + +func main() { + d := time.Millisecond * 300 + + ch := make(chan int) + i:=0 + for { + ctx, cancel := context.WithTimeout(context.Background(), d) + go work(i, ch) + select { + case x := <- ch: + fmt.Println("Received",x) + case <- ctx.Done(): + fmt.Println("Done!!") + } + if ctx.Err()!=nil{ + fmt.Println(ctx.Err()) + return + } + cancel() + i++ + } +} diff --git a/LectureCodeExamples/concurrency/context/with_value/main.go b/LectureCodeExamples/concurrency/context/with_value/main.go new file mode 100644 index 0000000000000000000000000000000000000000..2f814bf5f2327c0f42b0771e42c1837a62c1ef64 --- /dev/null +++ b/LectureCodeExamples/concurrency/context/with_value/main.go @@ -0,0 +1,29 @@ +package main + +import ( + "context" + "errors" + "fmt" +) + +func main() { + + f := func(ctx context.Context, a int, b int) (int,error) { + + switch ctx.Value("action") { + case "+": + return a + b,nil + case "-": + return a - b,nil + default: + return 0, errors.New("unknown action") + } + } + + ctx := context.WithValue(context.Background(), "action", "+") + r, err := f(ctx,22,20) + fmt.Println(r,err) + ctx2 := context.WithValue(context.Background(), "action", "-") + r, err = f(ctx2,22,20) + fmt.Println(r,err) +} diff --git a/LectureCodeExamples/concurrency/goroutines/example01/main.go b/LectureCodeExamples/concurrency/goroutines/example01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..3d7d2738ceb2fd7d7ecb60504971a3f3924e0e86 --- /dev/null +++ b/LectureCodeExamples/concurrency/goroutines/example01/main.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "time" +) + +func ShowIt() { + for { + time.Sleep(time.Millisecond * 100) + fmt.Println("Here it is!!!") + } +} + +func main() { + + go ShowIt() + + for i := 0; i < 5; i++ { + time.Sleep(time.Millisecond * 50) + fmt.Println("Where is it?") + } +} diff --git a/LectureCodeExamples/concurrency/goroutines/example02/main.go b/LectureCodeExamples/concurrency/goroutines/example02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..5759fc0353ba706d331b066e65c34536803a61c2 --- /dev/null +++ b/LectureCodeExamples/concurrency/goroutines/example02/main.go @@ -0,0 +1,21 @@ +package main + +import ( + "time" + "fmt" +) + +func ShowIt(t time.Duration, num int){ + for { + time.Sleep(t) + fmt.Println(num) + } +} + +func main() { + go ShowIt(time.Second, 100) + go ShowIt(time.Millisecond*500,10) + go ShowIt(time.Millisecond*250,1) + + time.Sleep(time.Millisecond*1200) +} diff --git a/LectureCodeExamples/concurrency/mutex/example_01/main.go b/LectureCodeExamples/concurrency/mutex/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..b9584f9cf4dd1e97b11b025d6459fc5d9cb28403 --- /dev/null +++ b/LectureCodeExamples/concurrency/mutex/example_01/main.go @@ -0,0 +1,41 @@ +package main + +import ( + "fmt" + "sync" + "time" +) + +func writer(x map[int]int, factor int, m *sync.Mutex) { + i := 1 + for { + time.Sleep(time.Second) + m.Lock() + x[i] = x[i-1] * factor + m.Unlock() + i++ + } +} + +func reader(x map[int]int, m *sync.Mutex) { + for { + time.Sleep(time.Millisecond*500) + m.Lock() + fmt.Println(x) + m.Unlock() + } +} + +func main() { + x := make(map[int]int) + x[0]=1 + + m := sync.Mutex{} + go writer(x, 2, &m) + go reader(x, &m) + + time.Sleep(time.Millisecond * 300) + go writer(x, 3, &m) + + time.Sleep(time.Second*4) +} diff --git a/LectureCodeExamples/concurrency/once/example_01/main.go b/LectureCodeExamples/concurrency/once/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..a3025680875f1cfb0d5d453105405d8f6c7c6ea9 --- /dev/null +++ b/LectureCodeExamples/concurrency/once/example_01/main.go @@ -0,0 +1,36 @@ +package main + +import ( + "fmt" + "math/rand" + "sync" + "time" +) + +var first int + +func setter(i int, ch chan bool, once *sync.Once) { + t := rand.Uint32() % 300 + time.Sleep(time.Duration(t)*time.Millisecond) + once.Do(func(){ + first = i + }) + ch <- true + fmt.Println(i,"Done") +} + +func main() { + rand.Seed(time.Now().UnixNano()) + + var once sync.Once + + ch := make(chan bool) + for i:=0;i<5;i++ { + go setter(i, ch, &once) + } + + for i:=0;i<5;i++{ + <- ch + } + fmt.Println("The first was", first) +} diff --git a/LectureCodeExamples/concurrency/select/example_01a/main.go b/LectureCodeExamples/concurrency/select/example_01a/main.go new file mode 100644 index 0000000000000000000000000000000000000000..056bd92f6c64ee3638ba243f11269354fee2aa44 --- /dev/null +++ b/LectureCodeExamples/concurrency/select/example_01a/main.go @@ -0,0 +1,40 @@ +package main + +import ( + "fmt" + "strconv" + "time" +) + +func sendNumbers(out chan int) { + for i:=0; i < 5; i++ { + time.Sleep(time.Millisecond * 500) + out <- i + } + fmt.Println("no more numbers") +} + +func sendMsgs(out chan string) { + for i:=0; i < 5; i++ { + time.Sleep(time.Millisecond * 300) + out <- strconv.Itoa(i) + } + fmt.Println("no more msgs") +} + +func main() { + numbers := make(chan int) + msgs := make(chan string) + + go sendNumbers(numbers) + go sendMsgs(msgs) + + for i:=0;i<10;i++ { + select { + case num := <- numbers: + fmt.Printf("number %d\n", num) + case msg := <- msgs: + fmt.Printf("msg %s\n", msg) + } + } +} diff --git a/LectureCodeExamples/concurrency/select/example_01b/main.go b/LectureCodeExamples/concurrency/select/example_01b/main.go new file mode 100644 index 0000000000000000000000000000000000000000..e38f13233e77a825b882205176594c69f9b844e3 --- /dev/null +++ b/LectureCodeExamples/concurrency/select/example_01b/main.go @@ -0,0 +1,52 @@ +package main + +import ( + "fmt" + "strconv" + "time" +) + +func sendNumbers(out chan int) { + for i:=0; i < 5; i++ { + time.Sleep(time.Millisecond * 500) + out <- i + } + fmt.Println("no more numbers") + close(out) +} + +func sendMsgs(out chan string) { + for i:=0; i < 5; i++ { + time.Sleep(time.Millisecond * 300) + out <- strconv.Itoa(i) + } + fmt.Println("no more msgs") + close(out) +} + +func main() { + numbers := make(chan int) + msgs := make(chan string) + + go sendNumbers(numbers) + go sendMsgs(msgs) + + closedNums, closedMsgs := false, false + + for !closedNums || !closedMsgs { + select { + case num, ok := <- numbers: + if ok { + fmt.Printf("number %d\n", num) + } else { + closedNums = true + } + case msg, ok := <- msgs: + if ok { + fmt.Printf("msg %s\n", msg) + } else { + closedMsgs = true + } + } + } +} diff --git a/LectureCodeExamples/concurrency/select/example_02/main.go b/LectureCodeExamples/concurrency/select/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..b13b3e1746206eb73aab34cfb807522fb43e10ce --- /dev/null +++ b/LectureCodeExamples/concurrency/select/example_02/main.go @@ -0,0 +1,29 @@ +package main + +import "fmt" + +func main() { + ch := make(chan int) + //ch := make(chan int,1) + + select { + case i := <-ch: + fmt.Println("Received", i) + default: + fmt.Println("Nothing received") + } + + select { + case ch <- 42: + fmt.Println("Send 42") + default: + fmt.Println("Nothing sent") + } + + select { + case i := <-ch: + fmt.Println("Received", i) + default: + fmt.Println("Nothing received") + } +} diff --git a/LectureCodeExamples/concurrency/timers_tickers_timeouts/example_01/main.go b/LectureCodeExamples/concurrency/timers_tickers_timeouts/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..4a195399d9469b2b7b1f305f310cb6538a6ee50b --- /dev/null +++ b/LectureCodeExamples/concurrency/timers_tickers_timeouts/example_01/main.go @@ -0,0 +1,33 @@ +package main + +import ( + "fmt" + "time" +) + +func worker(x *int) { + for { + time.Sleep(time.Millisecond * 500) + *x = *x + 1 + } +} + +func main() { + timer := time.NewTimer(time.Second * 5) + ticker := time.NewTicker(time.Second) + + x := 0 + go worker(&x) + + for { + select { + case <- timer.C: + fmt.Printf("timer -> %d\n", x) + case <- ticker.C: + fmt.Printf("ticker -> %d\n", x) + } + if x>=10 { + break + } + } +} diff --git a/LectureCodeExamples/concurrency/timers_tickers_timeouts/example_02/main.go b/LectureCodeExamples/concurrency/timers_tickers_timeouts/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..a69b6dc63ca105c44589ba29431498e6c778c097 --- /dev/null +++ b/LectureCodeExamples/concurrency/timers_tickers_timeouts/example_02/main.go @@ -0,0 +1,36 @@ +package main + +import ( + "fmt" + "time" +) + +func reaction(t *time.Ticker) { + for { + select { + case x := <-t.C: + fmt.Println("quick",x) + } + } +} + +func slowReaction(t *time.Timer) { + select { + case x := <-t.C: + fmt.Println("slow", x) + } +} + +func main() { + quick := time.NewTicker(time.Second) + slow := time.NewTimer(time.Second * 5) + stopper := time.NewTimer(time.Second * 4) + go reaction(quick) + go slowReaction(slow) + + <- stopper.C + quick.Stop() + + stopped := slow.Stop() + fmt.Println("Stopped before the event?",stopped) +} diff --git a/LectureCodeExamples/concurrency/waitgroup/example_01/main.go b/LectureCodeExamples/concurrency/waitgroup/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..cdba9916d5190ad01ac6c343abf837795b382bec --- /dev/null +++ b/LectureCodeExamples/concurrency/waitgroup/example_01/main.go @@ -0,0 +1,42 @@ +package main + +import ( + "fmt" + "math/rand" + "sync" + "time" +) + +func generator(ch chan int, wg *sync.WaitGroup) { + defer wg.Done() + for i:=0;i<5;i++ { + time.Sleep(time.Millisecond*200) + ch <- rand.Int() + } + close(ch) + fmt.Println("Generator done") +} + +func consumer(id int, sleep time.Duration, + ch chan int, wg *sync.WaitGroup) { + defer wg.Done() + for task := range(ch) { + time.Sleep(time.Millisecond*sleep) + fmt.Printf("%d - task[%d]\n",id,task) + } + fmt.Printf("Consumer %d done\n",id) +} + +func main() { + rand.Seed(42) + + ch := make(chan int,10) + var wg sync.WaitGroup + wg.Add(3) + + go generator(ch,&wg) + go consumer(1,400,ch,&wg) + go consumer(2,100,ch,&wg) + + wg.Wait() +} diff --git a/LectureCodeExamples/data_structures/interfaces/example_01/main.go b/LectureCodeExamples/data_structures/interfaces/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..4f64b713b355f995a68063b85804e596b043e34d --- /dev/null +++ b/LectureCodeExamples/data_structures/interfaces/example_01/main.go @@ -0,0 +1,40 @@ +package main + +import "fmt" + +type Animal interface { + Roar() string + Run() string +} + +type Dog struct {} + +func (d Dog) Roar() string { + return "woof" +} + +func (d Dog) Run() string { + return "run like a dog" +} + +type Cat struct {} + +func (c *Cat) Roar() string { + return "meow" +} + +func (c *Cat) Run() string { + return "run like a cat" +} + +func RoarAndRun(a Animal) { + fmt.Printf("%s and %s\n", a.Roar(), a.Run()) +} + +func main() { + myDog := Dog{} + myCat := Cat{} + + RoarAndRun(myDog) + RoarAndRun(&myCat) +} diff --git a/LectureCodeExamples/data_structures/interfaces/example_01a/main.go b/LectureCodeExamples/data_structures/interfaces/example_01a/main.go new file mode 100644 index 0000000000000000000000000000000000000000..dd43b7c9457de99ff27ec6dd0df6e5040dfaa982 --- /dev/null +++ b/LectureCodeExamples/data_structures/interfaces/example_01a/main.go @@ -0,0 +1,25 @@ +package main + +import "fmt" + +type Greeter interface { + SayHello() string +} + +type Person struct{ + name string +} + +func (p *Person) SayHello() string { + return "Hi! This is me "+ p.name +} + +func main() { + + var g Greeter + + p := Person{"John"} + // g = p --> Does not work + g = &p + fmt.Println(g.SayHello()) +} diff --git a/LectureCodeExamples/data_structures/interfaces/example_02/main.go b/LectureCodeExamples/data_structures/interfaces/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..9246204b20c5499fb10383a8ef1014cfa2fea596 --- /dev/null +++ b/LectureCodeExamples/data_structures/interfaces/example_02/main.go @@ -0,0 +1,15 @@ +package main + +import "fmt" + +func main() { + var aux interface{} + + fmt.Println(aux) + + aux = 10 + fmt.Println(aux) + + aux = "hello" + fmt.Println(aux) +} diff --git a/LectureCodeExamples/data_structures/interfaces/example_03/main.go b/LectureCodeExamples/data_structures/interfaces/example_03/main.go new file mode 100644 index 0000000000000000000000000000000000000000..924168877f2f2315684dd422ad63c1979e145790 --- /dev/null +++ b/LectureCodeExamples/data_structures/interfaces/example_03/main.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +func main() { + + aux := []interface{}{42, "hello", true} + + for _, i := range aux { + switch t := i.(type) { + default: + fmt.Printf("%T --> %s\n", t, i) + case int: + fmt.Printf("%T --> %d\n", t, i) + case string: + fmt.Printf("%T --> %s\n", t, i) + case bool: + fmt.Printf("%T --> %v\n", t, i) + } + } +} diff --git a/LectureCodeExamples/data_structures/methods/example_01/main.go b/LectureCodeExamples/data_structures/methods/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..ed63173a7e34ce47a9c30952ad83d89109cc363a --- /dev/null +++ b/LectureCodeExamples/data_structures/methods/example_01/main.go @@ -0,0 +1,17 @@ +package main + +import "fmt" + +type Rectangle struct{ + Height int + Width int +} + +func (r Rectangle) Surface() int { + return r.Height * r.Width +} + +func main() { + r := Rectangle{2,3} + fmt.Printf("rectangle %v has surface %d",r, r.Surface()) +} diff --git a/LectureCodeExamples/data_structures/methods/example_02/main.go b/LectureCodeExamples/data_structures/methods/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..63008d6edcf54ff7a60b2f78f3a6435b87059bc6 --- /dev/null +++ b/LectureCodeExamples/data_structures/methods/example_02/main.go @@ -0,0 +1,29 @@ +package main + +import "fmt" + +type Rectangle struct{ + Height int + Width int +} + +func (r Rectangle) Enlarge(factor int) { + r.Height = r.Height * factor + r.Width = r.Width * factor +} + +func (r *Rectangle) EnlargeP(factor int) { + r.Height = r.Height * factor + r.Width = r.Width * factor +} + +func main() { + rect := Rectangle{2,2} + fmt.Println(rect) + + rect.Enlarge(2) + fmt.Println(rect) + + rect.EnlargeP(2) + fmt.Println(rect) +} diff --git a/LectureCodeExamples/data_structures/methods/example_03/main.go b/LectureCodeExamples/data_structures/methods/example_03/main.go new file mode 100644 index 0000000000000000000000000000000000000000..e891f83bea34d3623a7ca23be28a156409ab3060 --- /dev/null +++ b/LectureCodeExamples/data_structures/methods/example_03/main.go @@ -0,0 +1,27 @@ +package main + +import "fmt" + +type Rectangle struct { + Height int + Width int +} + +func (r Rectangle) Surface() int { + return r.Height * r.Width +} + +type Box struct { + Rectangle + depth int +} + +func (b Box) Volume() int { + return b.Surface() * b.depth +} + +func main() { + b := Box{Rectangle{3,3}, 3} + fmt.Printf("%+v\n",b) + fmt.Println("Volume", b.Volume()) +} diff --git a/LectureCodeExamples/data_structures/structures/example_01/main.go b/LectureCodeExamples/data_structures/structures/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..1ebcb52cb8584f079e338f1f430b48e7175be0fa --- /dev/null +++ b/LectureCodeExamples/data_structures/structures/example_01/main.go @@ -0,0 +1,22 @@ +package main + +import "fmt" + +type Rectangle struct{ + Height int + Width int +} + +func main() { + a := Rectangle{} + fmt.Println(a) + + b := Rectangle{4,4} + fmt.Println(b) + + c := Rectangle{Width: 10, Height: 3} + fmt.Println(c) + + d := Rectangle{Width: 7} + fmt.Println(d) +} diff --git a/LectureCodeExamples/data_structures/structures/example_02/main.go b/LectureCodeExamples/data_structures/structures/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..8c2cae1838b1a4ffe67527a3085a79ff4ea359e4 --- /dev/null +++ b/LectureCodeExamples/data_structures/structures/example_02/main.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +type Rectangle struct{ + Height int + Width int +} + +func NewRectangle(height int, width int) *Rectangle { + return &Rectangle{height, width} +} + +func main() { + a := Rectangle{Height: 7} + fmt.Println(a) + + r := NewRectangle(2,3) + fmt.Println(r) + fmt.Println(*r) +} diff --git a/LectureCodeExamples/data_structures/structures/example_03/main.go b/LectureCodeExamples/data_structures/structures/example_03/main.go new file mode 100644 index 0000000000000000000000000000000000000000..0878638525d0999d07d1f7607e48fcf264734037 --- /dev/null +++ b/LectureCodeExamples/data_structures/structures/example_03/main.go @@ -0,0 +1,29 @@ +package main + +import ( + "fmt" + "reflect" +) + +type Circle struct { + x int + y int + radius int +} + +func main() { + ac := struct{x int; y int; radius int}{1,2,3} + c := Circle{10,10,3} + + fmt.Printf("%+v\n", ac) + fmt.Println(reflect.TypeOf(ac)) + fmt.Printf("%+v\n",c) + fmt.Println(reflect.TypeOf(c)) + + ac.x=3 + fmt.Printf("%+v\n", ac) + + ac = c + fmt.Printf("%+v\n", ac) + fmt.Println(reflect.TypeOf(ac)) +} diff --git a/LectureCodeExamples/data_structures/structures/example_04/main.go b/LectureCodeExamples/data_structures/structures/example_04/main.go new file mode 100644 index 0000000000000000000000000000000000000000..f0d3f2d5fc12e9baf54560b169c5f660536c8fd6 --- /dev/null +++ b/LectureCodeExamples/data_structures/structures/example_04/main.go @@ -0,0 +1,18 @@ +package main + +import "fmt" + +type Coordinates struct { + x int + y int +} + +type Circle struct { + center Coordinates + radius int +} + +func main() { + c := Circle{Coordinates{1, 2}, 3} + fmt.Printf("%+v\n", c) +} diff --git a/LectureCodeExamples/data_structures/structures/example_05/main.go b/LectureCodeExamples/data_structures/structures/example_05/main.go new file mode 100644 index 0000000000000000000000000000000000000000..f615d54a3244cedfe1e40358cc2e4b2779da4cb5 --- /dev/null +++ b/LectureCodeExamples/data_structures/structures/example_05/main.go @@ -0,0 +1,20 @@ +package main + +import "fmt" + +type Coordinates struct { + x int + y int +} + +type Circle struct { + Coordinates + radius int +} + +func main() { + c := Circle{Coordinates{1, 2}, 3} + fmt.Printf("%+v\n", c) + fmt.Printf("%+v\n", c.Coordinates) + fmt.Println(c.x, c.y) +} diff --git a/LectureCodeExamples/first_program/example_01/main.go b/LectureCodeExamples/first_program/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..3a7e9b3d9dfe64b27db6fcbc4ae9516e34328e43 --- /dev/null +++ b/LectureCodeExamples/first_program/example_01/main.go @@ -0,0 +1,7 @@ +package main + +import "fmt" + +func main() { + fmt.Println("Save the world with Go!!!") +} diff --git a/LectureCodeExamples/first_program/example_02/main.go b/LectureCodeExamples/first_program/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..834d560c13a4b51d433e254f77e17c4a112cdedb --- /dev/null +++ b/LectureCodeExamples/first_program/example_02/main.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + "os" +) + +func main() { + + argsWithProg := os.Args + argsWithoutProg := os.Args[1:] + + arg := os.Args[3] + + fmt.Println(argsWithProg) + fmt.Println(argsWithoutProg) + fmt.Println(arg) +} diff --git a/LectureCodeExamples/first_program/example_03/sum.go b/LectureCodeExamples/first_program/example_03/sum.go new file mode 100644 index 0000000000000000000000000000000000000000..27d234f21aba7f13d8bf229fdd46712007725d15 --- /dev/null +++ b/LectureCodeExamples/first_program/example_03/sum.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "os" + "strconv" +) + +func main() { + argsWithProg := os.Args + + numA, err := strconv.Atoi(argsWithProg[1]) + if err != nil { + fmt.Println(err) + os.Exit(2) + } + + numB, err := strconv.Atoi(argsWithProg[2]) + if err != nil { + fmt.Println(err) + os.Exit(2) + } + + result := numA + numB + fmt.Printf("%d + %d = %d\n", numA, numB, result) +} diff --git a/LectureCodeExamples/reflection/functions/example_01/main.go b/LectureCodeExamples/reflection/functions/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..5cc2a6bd1626461ad48f28529ab272e61f175122 --- /dev/null +++ b/LectureCodeExamples/reflection/functions/example_01/main.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" + "reflect" +) + + +func BuildAdder (i interface{}) { + fn := reflect.ValueOf(i).Elem() + + newF := reflect.MakeFunc(fn.Type(), func(in []reflect.Value)[]reflect.Value{ + + if len(in) > 2 { + return []reflect.Value{} + } + + a, b := in[0], in[1] + + if a.Kind() != b.Kind() { + return []reflect.Value{} + } + + var result reflect.Value + + switch a.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + result = reflect.ValueOf(a.Int() + b.Int()) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + result = reflect.ValueOf(a.Uint() + b.Uint()) + case reflect.Float32, reflect.Float64: + result = reflect.ValueOf(a.Float() + b.Float()) + case reflect.String: + result = reflect.ValueOf(a.String() + b.String()) + default: + result = reflect.ValueOf(interface{}(nil)) + } + return []reflect.Value{result} + }) + fn.Set(newF) +} + +func main() { + var intAdder func(int64,int64) int64 + var floatAdder func(float64, float64) float64 + var strAdder func(string, string) string + + BuildAdder(&intAdder) + BuildAdder(&floatAdder) + BuildAdder(&strAdder) + + fmt.Println(intAdder(1,2)) + fmt.Println(floatAdder(3.0,2.423)) + fmt.Println(strAdder("hello"," go")) +} diff --git a/LectureCodeExamples/reflection/functions/example_02/main.go b/LectureCodeExamples/reflection/functions/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..11e88b33a21f391c4716bc68abb09aa193dc4d98 --- /dev/null +++ b/LectureCodeExamples/reflection/functions/example_02/main.go @@ -0,0 +1,73 @@ +//package main +// +//import ( +// "fmt" +// "reflect" +//) +// +//type User struct { +// UserId string +// Email string +//} +// +//const Trojan int64 = 42 +// +//func NewStructCounter(i interface{}) interface{} { +// v := reflect.ValueOf(i) +// t := reflect.TypeOf(i) +// var stf []reflect.StructField +// +// counterField := reflect.StructField{ +// Name: "Trojan", +// Type: reflect.TypeOf(Trojan), +// } +// +// for i:=0;i<v.NumField();i++ { +// newField := reflect.StructField{ +// Name: t.Field(i).Name, +// Type: t.Field(i).Type, +// } +// stf = append(stf, newField) +// } +// stf = append(stf, counterField) +// +// newType := reflect.StructOf(stf) +// newStruct := reflect.New(newType).Interface() +// +// // build something new from the interface +// toReturn := reflect.ValueOf(newStruct) +// // fill it +// for i := 0; i<v.NumField(); i++ { +// toReturn.Elem().Field(i).Set(v.Field(i)) +// } +// // set trojan +// toReturn.Elem().FieldByName("Trojan").SetInt(Trojan) +// +// //return newStruct.Interface() +// return toReturn +//} +// +//func main() { +// u := User{"John", "john@gmail.com"} +// fmt.Println(u) +// +// uCounter := NewStructCounter(u) +// fmt.Println(uCounter) +// +// v := reflect.ValueOf(uCounter) +// fmt.Println(v) +// +// v.Field(2).SetInt(666) +// fmt.Println(uCounter) +// +// //sr := reflect.ValueOf(uCounter) +// //fmt.Println(sr.Elem().Field(0).Interface()) +// //sr.Elem().Field(0).Set(reflect.ValueOf("hola")) +// //fmt.Println(sr) +// +// //t := reflect.TypeOf(uCounter).Elem() +// //fmt.Println(t) +// //newU := reflect.New(t).Elem().Interface() +// //fmt.Println(newU) +// +//} diff --git a/LectureCodeExamples/reflection/reflect_type/example_01/main.go b/LectureCodeExamples/reflection/reflect_type/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..101216b049d04a847029cfca456c78b64322d78c --- /dev/null +++ b/LectureCodeExamples/reflection/reflect_type/example_01/main.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + "reflect" +) + +func main() { + var a int32 = 42 + var b string = "forty two" + + typeA := reflect.TypeOf(a) + fmt.Println(typeA) + + typeB := reflect.TypeOf(b) + fmt.Println(typeB) +} diff --git a/LectureCodeExamples/reflection/reflect_type/example_02/main.go b/LectureCodeExamples/reflection/reflect_type/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..647ae4fde692641ad505124ce135d0012cc4c7ef --- /dev/null +++ b/LectureCodeExamples/reflection/reflect_type/example_02/main.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "reflect" +) + +type T struct { + A int32 + B string +} + +func main() { + t := T{42, "forty two"} + + typeT := reflect.TypeOf(t) + fmt.Println(typeT) + + for i:=0;i<typeT.NumField();i++{ + field := typeT.Field(i) + fmt.Println(field.Name,field.Type) + } +} diff --git a/LectureCodeExamples/reflection/reflect_type/example_03/main.go b/LectureCodeExamples/reflection/reflect_type/example_03/main.go new file mode 100644 index 0000000000000000000000000000000000000000..206b41b7b94ccd0c9bb6393ace25171179096dd1 --- /dev/null +++ b/LectureCodeExamples/reflection/reflect_type/example_03/main.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + "reflect" +) + +type Adder interface{ + Add (int, int) int +} + +type Calculator struct{} + +func(c *Calculator) Add(a int, b int) int { + return a + b +} + +func main() { + + var ptrAdder *Adder + adderType := reflect.TypeOf(ptrAdder).Elem() + + c := Calculator{} + + calcType := reflect.TypeOf(c) + calcTypePtr := reflect.TypeOf(&c) + + fmt.Println(calcType, calcType.Implements(adderType)) + fmt.Println(calcTypePtr, calcTypePtr.Implements(adderType)) +} diff --git a/LectureCodeExamples/reflection/reflect_type/example_04/main.go b/LectureCodeExamples/reflection/reflect_type/example_04/main.go new file mode 100644 index 0000000000000000000000000000000000000000..0f6b3b4186dd58599151b231d64e38c8ad47c27c --- /dev/null +++ b/LectureCodeExamples/reflection/reflect_type/example_04/main.go @@ -0,0 +1,46 @@ +package main + +import ( + "fmt" + "reflect" + "strings" +) + +type T struct { + B int + C string +} + +type S struct { + C string + D T + E map[string]int +} + +func printerReflect(offset int, typeOfX reflect.Type) { + indent := strings.Repeat(" ",offset) + fmt.Printf("%s %s: %s {\n",indent, typeOfX.Name(), typeOfX.Kind()) + if typeOfX.Kind() == reflect.Struct { + for i:=0;i<typeOfX.NumField();i++{ + innerIndent := strings.Repeat(" ",offset+4) + f := typeOfX.Field(i) + if f.Type.Kind() == reflect.Struct { + printerReflect(offset+4, f.Type) + } else { + fmt.Printf("%s %s: %s\n",innerIndent, f.Name, f.Type) + } + } + } + fmt.Printf("%s }\n", indent) + +} + +func main() { + + x := S{"root", + T{42, "forty two"}, + make(map[string]int), + } + + printerReflect(0, reflect.TypeOf(x)) +} diff --git a/LectureCodeExamples/reflection/reflect_value/example_01/main.go b/LectureCodeExamples/reflection/reflect_value/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..89252125eb38e4eb69eafa31c8e45202348bf61b --- /dev/null +++ b/LectureCodeExamples/reflection/reflect_value/example_01/main.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + "reflect" +) + +func main() { + var a int32 = 42 + var b string = "forty two" + + valueOfA := reflect.ValueOf(a) + fmt.Println(valueOfA.Interface()) + + valueOfB := reflect.ValueOf(b) + fmt.Println(valueOfB.Interface()) +} diff --git a/LectureCodeExamples/reflection/reflect_value/example_02/main.go b/LectureCodeExamples/reflection/reflect_value/example_02/main.go new file mode 100644 index 0000000000000000000000000000000000000000..5caefa87d14f2a1790dac46dbad5f570da812cc7 --- /dev/null +++ b/LectureCodeExamples/reflection/reflect_value/example_02/main.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "reflect" +) + +func ValuePrint(i interface{}) { + v := reflect.ValueOf(i) + switch v.Kind() { + case reflect.Int32: + fmt.Println("Int32 with value", v.Int()) + case reflect.String: + fmt.Println("String with value", v.String()) + default: + fmt.Println("unknown type") + } +} + +func main() { + var a int32 = 42 + var b string = "forty two" + + ValuePrint(a) + ValuePrint(b) +} diff --git a/LectureCodeExamples/reflection/reflect_value/example_03/main.go b/LectureCodeExamples/reflection/reflect_value/example_03/main.go new file mode 100644 index 0000000000000000000000000000000000000000..689155ed7a050cae9873a239cb3da734e9a788e6 --- /dev/null +++ b/LectureCodeExamples/reflection/reflect_value/example_03/main.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "reflect" +) + +type T struct { + A int32 + B string + C float32 +} + +func main() { + t := T{42, "forty two", 3.14} + + valueT := reflect.ValueOf(t) + fmt.Println(valueT.Kind(), valueT) + + for i:=0;i<valueT.NumField();i++{ + field := valueT.Field(i) + fmt.Println(field.Kind(), field.String(), field.Interface()) + } +} + + diff --git a/LectureCodeExamples/reflection/reflect_value/example_04/main.go b/LectureCodeExamples/reflection/reflect_value/example_04/main.go new file mode 100644 index 0000000000000000000000000000000000000000..abc61f8f0b26f5c2b078bea365e0f45d6dacfa4d --- /dev/null +++ b/LectureCodeExamples/reflection/reflect_value/example_04/main.go @@ -0,0 +1,29 @@ +package main + +import ( + "fmt" + "reflect" + "strings" +) + +type T struct { + A string + B int32 + C string +} + +func main() { + t := T{"hello",42,"bye"} + fmt.Println(t) + + valueOfT := reflect.ValueOf(&t).Elem() + for i:=0; i< valueOfT.NumField(); i++ { + f := valueOfT.Field(i) + if f.Kind() == reflect.String { + current := f.String() + f.SetString(strings.ToUpper(current)) + } + } + + fmt.Println(t) +} diff --git a/LectureCodeExamples/reflection/reflect_value/example_05/main.go b/LectureCodeExamples/reflection/reflect_value/example_05/main.go new file mode 100644 index 0000000000000000000000000000000000000000..ad9f009d5e03267e37aeb9c63cf82721cd31d177 --- /dev/null +++ b/LectureCodeExamples/reflection/reflect_value/example_05/main.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + "reflect" + "strings" +) + +type T struct { + A string + B int32 + c string +} + +func main() { + t := T{"hello",42,"bye"} + fmt.Println(t) + + valueOfT := reflect.ValueOf(&t).Elem() + for i:=0; i< valueOfT.NumField(); i++ { + f := valueOfT.Field(i) + if f.Kind() == reflect.String { + if f.CanSet() { + current := f.String() + f.SetString(strings.ToUpper(current)) + } + } + } + fmt.Println(t) +} diff --git a/LectureCodeExamples/reflection/tags/example_01/main.go b/LectureCodeExamples/reflection/tags/example_01/main.go new file mode 100644 index 0000000000000000000000000000000000000000..6b4be258945067349c7746d985fe509db30d1b6e --- /dev/null +++ b/LectureCodeExamples/reflection/tags/example_01/main.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + "reflect" +) + +type User struct { + UserId string `tagA:"valueA1" tagB: "valueA2"` + Email string `tagB:"value"` + Password string `tagC:"v1 v2"` +} + +func main() { + T := reflect.TypeOf(User{}) + + fieldUserId := T.Field(0) + t := fieldUserId.Tag + fmt.Println("StructTag is:",t) + v, _ := t.Lookup("tagA") + fmt.Printf("tagA: %s\n", v) + + fieldEmail, _ := T.FieldByName("Email") + vEmail := fieldEmail.Tag.Get("tagB") + fmt.Println("email tagB:", vEmail) + + fieldPassword, _ := T.FieldByName("Password") + fmt.Printf("Password tags: [%s]\n",fieldPassword.Tag) + fmt.Println(fieldPassword.Tag.Get("tagC")) +} diff --git a/LectureCodeExamples/reflection/tests/main.go b/LectureCodeExamples/reflection/tests/main.go new file mode 100644 index 0000000000000000000000000000000000000000..dc8417be8fed0494f66e7a2c3712a6339b8814f1 --- /dev/null +++ b/LectureCodeExamples/reflection/tests/main.go @@ -0,0 +1,11 @@ +package main + +import ( + "reflect" +) + +func main() { + var a int32 = 42 + v := reflect.ValueOf(a) + v.SetInt(16) // <-- panic +}