go - 在 Go 中创建对象

标签 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
}

这两个有什么区别?规范的做法是什么?

最佳答案

惯例是编写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/

相关文章:

没有远程存储库的 Go 模块?

google-app-engine - 数据存储四舍五入的时间字段

go - 在Golang中封装 `sort`接口(interface)

amazon-web-services - AWS ECS SDK.使用 SDK 为 ECS 集群注册新的容器实例 (EC2)

google-app-engine - App Engine 部署到不是 project_id.appspot.com 的地方

go - 将 base64 字符串转换为 JPG

go - 如何将ClickHouse的groupArray函数的结果初始化为数组

go - Golang 中的 RLock() 和 Lock() 有什么区别?

go - 我可以在一台服务器上托管 Angular2 前端和 Golang 后端吗

go - 如何从 go-sqlite3 查询中获取计数值?