import "fmt"
type MyStruct struct {
Queue []string
}
func main() {
myStruct := &MyStruct{}
// Pre-allocate a slice with a capacity of 5
queue := make([]string, 0, 5)
myStruct.Queue = queue
// Add elements to the "end" of the queue
myStruct.Queue = append(myStruct.Queue, "1")
myStruct.Queue = append(myStruct.Queue, "2")
myStruct.Queue = append(myStruct.Queue, "3")
// queue: [1 2 3]
fmt.Println(myStruct.Queue)
fmt.Println(queue)
// Add another element
queue = append(queue, "4")
fmt.Println(queue)
queue = append(queue, "5")
fmt.Println(queue)
// queue: [1 2 3] ? or [1 2 3 4 5] ?
fmt.Println(myStruct.Queue)
// [ 4 5 3 ]
}
I expected [1,2,3] or [1,2,3,4,5] but, its [4, 5, 3]
when I changed Capacity of []string as 0, it was [1 ,2, 3]. because its reference pointer address change ([]string length > capacity).
by the way, I don’t understand what its [4, 5, 3]
>Solution :
queue := make([]string, 0, 5)
Makes an anonymous array with a size of 5, and creates the slice queue
that points to the beginning of that array, has a capacity of 5, and a length of 0.
myStruct.Queue = queue
Copies the slice-header queue
into myStruct.Queue
. myStruct.Queue
now points to the beginning of the same array, has a capacity of 5, and a length of 0.
myStruct.Queue = append(myStruct.Queue, "1")
myStruct.Queue = append(myStruct.Queue, "2")
myStruct.Queue = append(myStruct.Queue, "3")
Appends three elements to myStruct.Queue
. Since space is available, these elements are inserted into the existing array, which now contains ["1" "2" "3" "" ""]
. myStruct.Queue
‘s length is now 3. queue
still points to the same array, but its length is still 0.
queue = append(queue, "4")
queue = append(queue, "5")
Appends two elements to queue
. Space is available in the backing array, and queue
has a length of zero, so these two elements are inserted into the first two indices of the array, overwriting "1"
and "2"
.
Now the array contains ["4" "5" "3" "" ""]
. queue
is a view into that array with a length of 2, so it contains ["4" "5"]
. myStruct.Queue
is a view into the same array with a length of 3, so it contains ["4" "5" "3"]
.