我是第一次玩围棋。考虑这个例子。
type Foo struct {
Id int
}
func createFoo(id int) Foo {
return Foo{id}
}
这对于小对象来说完全没问题,但是如何为大对象创建工厂函数呢?
在这种情况下,最好返回指针以避免复制大块数据。
// now Foo has a lot of fields
func createFoo(id int /* other data here */) *Foo {
x := doSomeCalc()
return &Foo{
Id: id
//X: x and other data
}
}
或
func createFoo(id int /* other data here */) *Foo {
x := doSomeCalc()
f := new(Foo)
f.Id = id
//f.X = x and other data
return f
}
这两个有什么区别?规范的做法是什么?
最佳答案
惯例是编写NewFoo
函数来创建和初始化对象。示例:
如果您愿意,您总是可以返回指针,因为在访问方法或属性时没有语法差异。我什至会说返回指针通常更方便,这样您就可以直接在返回的对象上使用指针接收方方法。想象一下这样的基地:
type Foo struct{}
func (f *Foo) M1() {}
返回对象时不能这样做,因为返回值不可寻址(example on play):
NewFoo().M1()
当返回一个指针时,你可以这样做。 ( example on play )
关于go - 在 Go 中创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24993816/