Golang Beginner Snippets
Play here: Go Playground (opens in a new tab)
Conditional flow
if 1 == 2 {
}
Loop
For Loop
for i := 0; i < 10; i++ {
fmt.Println(i)
}
While Loop
stack := []int{}
for len(stack) > 0 {
}
For-in
arr := []string{}
for index, item := range arr {
// do something
}
Array & Map
Array Length
arr := []int{1, 2, 3}
fmt.Println(len(arr))
Array Push (Append)
arr := []int{1, 2, 3}
arr = append(arr, 4)
Assign Value to Map
m := make(map[string]int)
m["key"] = 1
fmt.Println(m)
Print Struct
log.Printf("%+v\n", res)
fmt.Printf("%+v\n", res)
Iterate over a Map
var employee = map[string]int{"Mark": 10, "Sandy": 20,
"Rocky": 30, "Rajiv": 40, "Kate": 50}
for key, element := range employee {
fmt.Println("Key:", key, "=>", "Element:", element)
}
Goroutine & Channel
Basic
func TestChannel(t *testing.T) {
channel := make(chan string)
defer close(channel)
go func() {
time.Sleep(1 * time.Second)
channel <- "Hello channel"
fmt.Println("Channel data sent")
}()
data := <-channel
fmt.Println(data)
}
Output
Channel data sent
Hello channel
Channel In & Out
func OnlyIn(channel chan<- string) {
channel <- "Only in"
}
func OnlyOut(channel <-chan string) {
data := <-channel
fmt.Println(data)
}
Buffered Channel
channel := make(chan string, 3)
defer close(channel)
channel <- "Hello 1"
channel <- "Hello 2"
channel <- "Hello 3"
channel <- "Hello 4"
fmt.Println("finish")
Output:
n/a
Error timeout to wait blocking process because there's no receiver on the channel. If the size is greater or equal 4, then there's no error.