I'm trying to build a LIFO stack. I've created a Stack[T any] interface and a dynamicStack[T any] struct. dynamicStack has a data []T field and an index int field. When a dynamicStack is created, I want data to be initialized empty, of fixed size 1 and type T. Statement comes up: "cannot use [0]T{} (value of type [0]T) as []T value in assignment" when I try to do so.
type Stack[T any] interface {
IsEmpty() bool
SeeTop() T
AddToStack(T)
Unstack() T
}
type dynamicStack[T any] struct {
data []T
index int
}
func CreateDynamicStack[T any]() Stack[T] {
s := new(dynamicStack[T])
s.data = [0]T{} // Problem
s.index = 0
return s
}
I've tried using const instead of "0", different sizes and even initializing the array as non-empty but nothing works.
I'm not trying to use append() method and I need a fixed size array as my plan is to resize the array whenever it's full or whenever it's half empty.
Any ideas?
s.datais a slice, you should initialize it as a slice :Actually, go handles a nil slice pretty much like an empty slice, so you don't even need to initialize
s.datain your structure. See the example below for an illustration.In go, there is a difference between a slice type
[]Tand an array type[n]T.For a detailed explanation of how slices and arrays behave, see this article by Andrew Gerrand:
Go Slices: usage and internals
playground: https://go.dev/play/p/kB1g2Iq-n6u