duanraa1984 2015-04-16 20:54
浏览 60
已采纳

Golang结构构造通用性

I have a struct that two other objects implement. In this case, typeA and B repo's. There's some initialization code, which are represented as ellipses here. The initialization code is completely duplicated between both constructors, and isn't a big deal while I only have two dbRepo's, but as I create more I will worry a bit more about the bad practice. Is there any way to generalize this with an interface?

type dbRepo struct {
    foo string
    bar string
}

type typeARepo dbRepo
type typeBRepo dbRepo

func newTypeARepo(foo, bar string) {
    ...
}

func newTypeBRepo(foo, bar string) {
    ...
}
  • 写回答

3条回答 默认 最新

  • dsbo44836129 2015-04-16 21:01
    关注

    The practice I've personally observed in Go (and it's also what's recommended in the effective Go or getting started with Go tutorials) is just to define a NewdbRepo function and use it for all instantation. It's implementation would look something like;

    func NewdbRepo(f, b string) *dbRepo {
        return &dbRepo{ foo:f, bar:b}
    }
    

    You can't actually define a constructor as you do in most C like languages so you just gotta provide a package scoped method to do construction for you. Also, if you're not using composite literals (the initilization style I use in my NewdbRepo implementation) then you may find that alone concise enough for your needs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊