New to Golang. If I want to construct 10 different variables using a forloop by the index (example below), what is the most efficient way to concatenate the index and the variable name? Obviously the following approach is incorrect.
for i := 0; i < 10; i++ {
user + i:= CreateUser("user_num_" + i)
user + i + bytes, _ := json.Marshal(&user + i)
}
You are looking for slices:
users := make([]User, 10)
for i := 0; i < 10; i++ {
users[i] = CreateUser(fmt.Sprintf("user_num_%d", i))
bytes, err := json.Marshal(users[i])
// TODO: handle err
fmt.Printf("OK: user[%d] = %s
", i, string(bytes))
}
Like their underlying array structure, slices allow you to store an ordered sequence of items and refer to them by their index.