我是第一次尝试使用Go语言。考虑以下示例。
或者
这两者有何不同?哪种是规范的方法?
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
}
这两者有何不同?哪种是规范的方法?