如何在没有构造函数的情况下在 Go 内部切片中正确初始化结构
How to properly init structs in Go inside slices without constructors
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 的幂。
你从未真正初始化过它。分配切片只是分配 space,但不会初始化单个元素。一旦你有了切片,你就可以遍历它并初始化:
func main() {
someSlice := make([]SomeStruct, 10)
for i:=range someSlice {
someSlice[i].q=*New[int]()
}
fmt.Println("Size of a buf: ", len(someSlice[0].q.buf))
}
您还可以这样做:
func (s *SomeStruct) Init() {
s.q=Queue[int]{
buf: make([]int, minQueueLen),
}
}
func main() {
someSlice := make([]SomeStruct, 10)
for i:=range someSlice {
someSlice[i].Init()
}
fmt.Println("Size of a buf: ", len(someSlice[0].q.buf))
}
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 的幂。
你从未真正初始化过它。分配切片只是分配 space,但不会初始化单个元素。一旦你有了切片,你就可以遍历它并初始化:
func main() {
someSlice := make([]SomeStruct, 10)
for i:=range someSlice {
someSlice[i].q=*New[int]()
}
fmt.Println("Size of a buf: ", len(someSlice[0].q.buf))
}
您还可以这样做:
func (s *SomeStruct) Init() {
s.q=Queue[int]{
buf: make([]int, minQueueLen),
}
}
func main() {
someSlice := make([]SomeStruct, 10)
for i:=range someSlice {
someSlice[i].Init()
}
fmt.Println("Size of a buf: ", len(someSlice[0].q.buf))
}