Go By Example 1
Learning to go
import (
"encoding/json"
"fmt"
"strconv"
"strings"
)
a := [7]string{"sun", "mon", "tues", "wednes", "thurs", "fri", "satur"}
res := make([]string, 0)
for i := range a {
s := "DAY " + strconv.Itoa(i) + ": " + strings.Title(a[i]) + "day"
res = append(res, s)
}
resB, _ := json.Marshal(res)
fmt.Println(string(resB))
-
First, we declare a new array
a
of type [7]string, which means it can hold 7 string values. We also initialize it with the values of a partial name of days. -
Then, we create a new slice with a length of 0 and a capacity of 0.
-
Then we use
range
to iterate over elements in the arraya
. As we don't need the value for each entry, we ignore the second argument and only specify the indexi
. -
Within the for loop, we declare and initialize a string with a formatted message, which would print something like "Day 1: Sunday". We use the
Itoa
function from thestrconv
package to convert an integer to string type, to allow the concatenation of two data structures (int and string). We also use a function in the built-instrings
package to capitalize each day. -
Then, we use the
append
function, which does not modify the slice in place. Instead, it returns a new slice with the appended element(s). In order to append an element to theres
slice, we will need to assign the returned slice back to theres
variable. So we call theappend
function with the slice and thes
variable as separate arguments. -
Then, we exit the loop and move on. To encode data in json, we use the
json.Marshal
function to convert theres
slice into a JSON byte slice ([]byte). The _ is known as the "blank identifier" and is used to discard the second return value of thejson.Marshal
function, which is an error value. If the function succeeds, the error value will be nil, so discarding it is safe in this case. -
Lastly, we convert the
resB
byte slice into a string and prints it to the console using thefmt.Println
function. The output will be a JSON-formatted string representation of theresB
slice, like so:
make run
["DAY 0: Sunday","DAY 1: Monday","DAY 2: Tuesday","DAY 3: Wednesday","DAY 4: Thursday","DAY 5: Friday","DAY 6: Saturday"]
To me, learning go is like learning how to express an abstract idea or an instruction in one line. However, if we want to go deep (pun intended :D), we should be able to expand this compact form into a narrative that is easy to follow.