如何在没有构造函数的情况下在 Go 中正确初始化切片内的结构
Go 没有构造函数,所以我想知道如何正确初始化切片内的结构。我很难相信答案是初始化并复制所有结构两次?
package main
import "fmt"
// minQueueLen is smallest capacity that queue may have.
// Must be power of 2 for bitwise modulus: x % n == x & (n - 1).
const minQueueLen = 16
type Queue[T any] struct {
buf []T
}
func New[T any]() *Queue[T] {
return &Queue[T]{
buf: make([]T, minQueueLen),
}
}
type SomeStruct struct {
q Queue[int]
}
func main() {
someSlice := make([]SomeStruct, 10)
// Now buf is the wrong size because we didn't
// get to init it with the proper constructor.
// It would be very wasteful to initialize this
// struct twice (100s of thousands or more).
fmt.Println("Size of a buf: ", len(someSlice[0].q.buf))
}
下面是一个示例,其中队列的缓冲区必须是 2 的幂。
Go doesn't have constructors so I'm wondering how you would properly initialize a struct inside a slice. I have trouble believing that the answer would be to initialize and copy all the structs twice?
package main
import "fmt"
// minQueueLen is smallest capacity that queue may have.
// Must be power of 2 for bitwise modulus: x % n == x & (n - 1).
const minQueueLen = 16
type Queue[T any] struct {
buf []T
}
func New[T any]() *Queue[T] {
return &Queue[T]{
buf: make([]T, minQueueLen),
}
}
type SomeStruct struct {
q Queue[int]
}
func main() {
someSlice := make([]SomeStruct, 10)
// Now buf is the wrong size because we didn't
// get to init it with the proper constructor.
// It would be very wasteful to initialize this
// struct twice (100s of thousands or more).
fmt.Println("Size of a buf: ", len(someSlice[0].q.buf))
}
Here is an example where the buffer of the queue must be a power of 2.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你从未真正初始化过它。分配切片只是分配空间,但不会初始化各个元素。获得切片后,您可以循环遍历它并初始化:
您还可以执行以下操作:
You never really initialized it. Allocating a slice simply allocates the space, but does not initialize individual elements. Once you have the slice, you can loop through it and inialize:
You can also do: