代码之家  ›  专栏  ›  技术社区  ›  nanobar

如何在没有构造函数的情况下正确初始化内部切片中的结构

go
  •  0
  • nanobar  · 技术社区  · 3 年前

    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的幂。

    1 回复  |  直到 3 年前
        1
  •  0
  •   Burak Serdar    3 年前

    你从未真正初始化过它。分配一个片只是分配空间,但不初始化单个元素。一旦你有了切片,你可以通过它循环并初始化:

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