When trying to mimic the queue interface in go lang, in Enque method i was appending variadic arguments directly to the slice. But when retrieved in Deque operation the type assertion was giving panic error. How appending variadic arguments directly to slice different from adding them individually ?
type Queue struct {
queueItems []Item
}
func (queue *Queue) Enque(items ...Item) error {
...
queue.queueItems = append(queue.queueItems, items)
...
}
....
queue.Enque(200)
val := queue.Deque()
otherVal := val.(int)
.....
Below code for Enque works fine
func (queue *Queue) Enque(items ...Item) error {
....
for _, itemVal := range items {
queue.queueItems = append(queue.queueItems, itemVal)
}
....
}
When you define a variadic formal parameter for a function, the underlying type of the actual parameter when you're using it in the function is a slice of whatever type you stated. In this case, the formal parameter
items
inEnqueue
when used in the function resolves to the type of[]Item
(slice ofItem
).So when you write
queue.queueItems = append(queue.queueItems, items)
what you're really saying is append this entire slice of items as a singular element onto my slice.What you meant to do was append each item from the variadic parameter as individual elements on your slice, which you can achieve by the following:
queue.queueItems = append(queue.queueItems, items...)