我正在学习 Golang,我正在尝试构建一个 LIFO 堆栈。我创建了一个 Stack[Tany] 接口和一个dynamicStack[Tany] 结构。 DynamicStack 有一个 data []T 字段和一个索引 int 字段。创建动态堆栈时,我希望数据初始化为空,固定大小为 1,类型为 T。出现语句:“不能使用 [0]T{}(类型 [0]T 的值)作为 []T 值当我尝试这样做时“作业”。
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
}
我尝试过使用 const 而不是“0”,不同的大小,甚至将数组初始化为非空,但没有任何效果。
我不想使用append()方法,我需要一个固定大小的数组,因为我的计划是在数组已满或半空时调整数组的大小。
有什么想法吗?
PD:这是我关于 SO 的第一篇文章,请告诉我是否可以做任何事情来改进有关该问题的结构/数据。谢谢:D
s.data
是一个切片,您应该将其初始化为切片:
s.data = make([]T, 0)
实际上,go 处理 nil 切片非常像处理空切片,因此您甚至不需要在结构中初始化
s.data
。请参阅下面的示例进行说明。
在Go中,切片类型
[]T
和数组类型[n]T
之间有区别。
有关切片和数组行为方式的详细说明,请参阅 Andrew Gerrand 的这篇文章:
Go Slices:用法和内部结构
// example of slice usage:
func testSlice() {
var s []int
fmt.Println("length:", len(s))
for i, x := range s {
fmt.Println("iterating:", i, x) // never executed, the slice is empty
}
newSlice := append(s, 1) // a slice allocation happens here
fmt.Println("result of append(s,1):", newSlice)
emptySlice := make([]int, 0)
// the only visible different thing is comparing to nil:
if s == nil {
fmt.Println("s is nil")
}
if emptySlice == nil {
fmt.Println("emptySlice is nil") // not printed
}
// if you stick to checking the *length* of your slice, you will
// have a consistent behavior:
if len(s) == 0 {
fmt.Println("s is empty")
}
if len(emptySlice) == 0 {
fmt.Println("emptySlice is empty")
}
}