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 的冪。
uj5u.com熱心網友回復:
你從來沒有真正初始化它。分配切片只是分配空間,但不會初始化單個元素。獲得切片后,您可以遍歷它并初始化:
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))
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/436597.html
標籤:走
上一篇:使用gorm插入表時外鍵約束失敗
下一篇:使用同步包中斷鏈接方法
