Interfacing non local types in golang

blov · 2017-03-11 01:00:08 · 1012 次点击    
这是一个分享于 2017-03-11 01:00:08 的资源,其中的信息可能已经有所发展或是发生改变。

Hi,

i have a question for all you golang ninjas! :smile:

In my api code i am using the MongoDB driver mgo. I initialize the mgo.Session and mgo.Database in the InitSession method in model/db.go.

I wrote a Datastore interface to distribute the database connection to all model methods that need db access. Now i have the following problem. My model methods cannot extend the type (db *mgo.Database) since it is no local type. Aliasing the mgo.Database type wouldn't help either since i need also access to the mgo.Database methods. I came up with an solution which feels dirty to me by wrapping the mgo.Database struct inside my own Database struct.

Is there a more elegant solution for this problem?

Here is the code fragment: https://gist.github.com/gdenn/24f787b2cbf5d51879ffb14036cd5e02


评论:

radovskyb:

What you are doing is fine from what I can see in that snippet.

It's actually a good practice to wrap your database types in your own types that implement interfaces as it makes it quite easy to swap out for different implementations if needed.

I'm not sure what other types of "extending" you need to do with your mongo database, but for that, it looks good.

Here is an example of something similar I wrote a while back (needs some work, was out of boredom):

Edit: I do however suggest separating concerns a little bit better. Rather than having a single Datastore interface in a single models package, it might be better to create a separate UserStore which has it's own interface.

Otherwise your models package might get quite cluttered in a big application.

rap3:

thanks radovskyb, i see your point for the interface seperation.

dchapes:

own types that inherit from interfaces

It's not helpful to misuse the word "inherit" here. Go does not have inheritance; it does have composition via embedding.

radovskyb:

This is true and I should have said implements interfaces, but we are all human and make mistakes :P

I edited it anyway because you are right even if we are being slightly pedantic about the point here lol!


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1012 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传