在Go语言中,可以通过make()函数调用结构体的构造函数吗?

huangapple go评论79阅读模式
英文:

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 &quot;sync&quot;

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

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

func main() {
    n := 10
    things := make([]*Thing, n)
    for i := 10; i &lt; 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 (
	&quot;fmt&quot;
	&quot;sync&quot;
)

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

func NewThing() *Thing {
	return &amp;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(&quot;things: &quot;, len(things))
	for _, thing := range things {
		fmt.Println(thing)
	}
}

Output:

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

huangapple
  • 本文由 发表于 2013年5月5日 07:12:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/16379804.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定