英文:
Is it possible to call a struct constructor through make() in go?
问题
有没有更好的方法来分配这个数组的内容,比如自动调用NewThing()
构造函数而不是手动构造每个元素?
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()
}
}
我意识到我正在分配一个指针数组,我的其他尝试都不成功,data通道没有初始化。这只是一个假设的例子。
谢谢!
英文:
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!
答案1
得分: 0
你可以简单地写成:
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)
}
}
输出:
things: 3
&{0xc200061020 0xc200062000}
&{0xc200061040 0xc200062060}
&{0xc200061060 0xc2000620c0}
英文:
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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论