diff --git a/README.md b/README.md index 784e9c2..553d16c 100644 --- a/README.md +++ b/README.md @@ -4847,6 +4847,145 @@ func main() { Since the first iota is declared with the value `3` (` + 3`), the next one has the value `4` +
+What will be the output of the following block of code?: + +``` +package main + +import ( + "fmt" + "sync" + "time" +) + +func main() { + var wg sync.WaitGroup + + wg.Add(1) + go func() { + time.Sleep(time.Second * 2) + fmt.Println("1") + wg.Done() + }() + + go func() { + fmt.Println("2") + }() + + wg.Wait() + fmt.Println("3") +} +``` +
+ +Output: 2 1 3 + +[Aritcle about sync/waitgroup](https://tutorialedge.net/golang/go-waitgroup-tutorial/) + +[Golang package sync](https://golang.org/pkg/sync/) +
+ +
+What will be the output of the following block of code?: + +``` +package main + +import ( + "fmt" +) + +func mod1(a []int) { + for i := range a { + a[i] = 5 + } + + fmt.Println("1:", a) +} + +func mod2(a []int) { + a = append(a, 125) // ! + + for i := range a { + a[i] = 5 + } + + fmt.Println("2:", a) +} + +func main() { + sl := []int{1, 2, 3, 4} + mod1(s1) + fmt.Println("1:", s1) + + s2 := []int{1, 2, 3, 4} + mod2(s2) + fmt.Println("2:", s2) +} +``` +
+ +Output:
+1 [5 5 5 5]
+1 [5 5 5 5]
+2 [5 5 5 5 5]
+2 [1 2 3 4]
+
+ +In `mod1` a is link, and when we're using `a[i]`, we're changing `s1` value to. +But in `mod2`, `append` creats new slice, and we're changing only `a` value, not `s2`. + +[Aritcle about arrays](https://golangbot.com/arrays-and-slices/), +[Blog post about `append`](https://blog.golang.org/slices) +
+ +
+What will be the output of the following block of code?: + +``` +package main + +import ( + "container/heap" + "fmt" +) + +// An IntHeap is a min-heap of ints. +type IntHeap []int + +func (h IntHeap) Len() int { return len(h) } +func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } +func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } + +func (h *IntHeap) Push(x interface{}) { + // Push and Pop use pointer receivers because they modify the slice's length, + // not just its contents. + *h = append(*h, x.(int)) +} + +func (h *IntHeap) Pop() interface{} { + old := *h + n := len(old) + x := old[n-1] + *h = old[0 : n-1] + return x +} + +func main() { + h := &IntHeap{4, 8, 3, 6} + heap.Init(h) + heap.Push(h, 7) + + fmt.Println((*h)[0]) +} +``` +
+ +Output: 3 + +[Golang container/heap package](https://golang.org/pkg/container/heap/) +
## Mongo