Is it possible to call the constructor constructor via make () in go?

Is there a better way to highlight the contents of this array, for example, by automatically calling the NewThing() constructor instead of manually creating 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 understand that I allocate an array of pointers, my other attempts were unsuccessful, and the data was not an initialized channel. This is just a contrived example.

Thanks!

+4
source share
1 answer

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} 
0
source

Source: https://habr.com/ru/post/1479192/


All Articles