Search code examples
gosemantics

Is it possible to call a struct constructor through make() in go?


Is there a better way to allocate the contents of this array, such as automatically calling the NewThing() constructor instead of manually constructing each element?

package main

import "sync"

type Thing struct {
    lock *sync.RWMutex
    data chan int
}

func NewThing() *Thing {
    return &Thing{ lock: new(sync.RWMutex), data: make(chan int) }
}

func main() {
    n := 10
    things := make([]*Thing, n)
    for i := 10; i < n; i++ {
        things[i] = NewThing()
    }
}

I realize i'm allocating an array of pointers, my other attempts were unsuccessful and data was not an initialized channel. This is just a contrived example.

Thanks!


Solution

  • You can simply write:

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    type Thing struct {
        lock *sync.RWMutex
        data chan int
    }
    
    func NewThing() *Thing {
        return &Thing{lock: new(sync.RWMutex), data: make(chan int)}
    }
    
    func NewThings(n int) []*Thing {
        things := make([]*Thing, n)
        for i := range things {
            things[i] = NewThing()
        }
        return things
    }
    
    func main() {
        things := NewThings(3)
    
        fmt.Println("things: ", len(things))
        for _, thing := range things {
            fmt.Println(thing)
        }
    }
    

    Output:

    things:  3
    &{0xc200061020 0xc200062000}
    &{0xc200061040 0xc200062060}
    &{0xc200061060 0xc2000620c0}