I am trying to use slice of type struct. Look at the following sample
package main
import (
"fmt"
)
func main() {
arr := []struct {
A string
B string
} {}
arr[0].A = "I am"
arr[0].B = "First"
arr[1].A = "I am"
arr[1].B = "Second"
fmt.Println(arr)
}
When I compile this code I've got out of range error. Why?
You need to append new elements to your slice (if you don't make an array as in FUZxxl's answer.
It is easier with a named type instead of a type literal.
See "Appending to and copying slices" and "Arrays, slices (and strings): The mechanics of 'append'".
Example play.golang.org
package main
import (
"fmt"
)
func main() {
type T struct {
A string
B string
}
arr := []T{}
arr = append(arr, T{A: "I am", B: "First"})
arr = append(arr, T{A: "I am", B: "Second"})
fmt.Println(arr)
}
Output:
[{I am First} {I am Second}]
You have created a slice with 0 (zero) elements. Access to elements at indices 0
and 1
is invalid. You probably wanted something like this:
arr := make([]struct{ A, B string }, 2)
Go slices do not automatically expand themselves to make room for more entries.