I have golang code scores := new([]int)
, I’m really confusing with this how we can use the scores variable for storing scores of a match
The built-in function
new
takes a typeT
, allocates storage for a variable of that type at run time, and returns a value of type*T
pointing to it.
We can split this:
type intslice []int
func main() {
scores := new(intslice)
fmt.Printf("%T %v\n", scores, scores)
}
Output:
*main.intslice &[]
Let’s add some int
s to it:
t := append(*scores, 1, 2, 3)
scores = &t
fmt.Printf("%T %v\n", scores, scores)
Output:
*main.intslice &[1 2 3]
How this way make arrays instead of slices
Well, an array has a fixed size. So an array of 10 ints has type [10]int
, but you do not need new()
to create it.
A simple example can be seen here:
Do you need an array with a fixed size? Or do you need a slice that can be appended to? Depending on the answer Go provides different keywords and different syntax.