初始化具有结构内部大小的通用切片[重复]

问题描述 投票:0回答:1

我正在尝试构建一个 LIFO 堆栈。我创建了一个

Stack[T any]
接口和
dynamicStack[T any]
结构。 DynamicStack 有一个数据
[]T
字段和一个索引
int
字段。创建
dynamicStack
时,我希望数据初始化为空,固定大小为 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()
方法,我需要一个固定大小的数组,因为我的计划是在数组已满或半空时调整数组大小。

有什么想法吗?

go generics stack abstract-data-type
1个回答
2
投票

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")
    }
}

游乐场:https://go.dev/play/p/kB1g2Iq-n6u

© www.soinside.com 2019 - 2024. All rights reserved.