英文:
Go: How to resolve dependency for structs passing between two packages as params?
问题
以下是翻译的内容:
不知道如何最好地组织结构以避免循环依赖。我有一个user
包,其中包含一个公开的UserService
,它接受一个存储器,因为它需要访问数据库,但它也有一些结构体。
package user
type UserParams struct {
Client util.HTTPExecutor
Store store.Store
...
}
func NewUserService(params *UserServiceParams) *UserService {...}
type User struct {
ID int32 `db:"id" json:"id"`
Name string `db:"name" json:"name"`
}
同时,我有一个存储器包,其中有一个接口,接受一些用户结构体并将其保存到数据库中。
package store
type Store interface {
UpdateUser(ctx context.Context, u *user.User) error
}
以下哪种方式更合理:
- 将
User
结构体移动到存储器包中(后者可能会有很多不同产品组件的这些结构体)。 - 将
User
结构体移动到一个单独的公共包中,以便这两个包都可以访问它。 - 将
User
结构体移动到user
包下的一个名为userstruct
的包中。
谢谢!
英文:
Don’t know what’s the best practice to structure this so I don’t have cyclic dependency, I have a user
package which exposes UserService
which takes a store because it needs to access database, but it also has some structs
package user
type UserParams struct {
Client util.HTTPExecutor
Store store.Store
...
}
func NewUserService(params *UserServiceParams) *UserService {...}
type User struct {
ID int32 `db:"id" json:"id"`
Name string `db:"name" json:"name"`
}
At the same time I have a store package which has an interface takes some user structs and save into the database.
package store
type Store interface {
UpdateUser(ctx context.Context, u *user.User) error
}
Does it make more sense to
- Move
User
struct into store package (latter might end up a lot of those structs for different product components) - Move
User
struct into a separate common package so both packages have access to it - Move
User
struct into a packageuserstruct
underuser
package
Thank you!
答案1
得分: 1
首先,这个问题有点主观,因为它在很大程度上取决于你的项目以及项目的布局。话虽如此,如果我是你,我会这样做。
考虑添加一个types
包。types
包很少依赖其他任何东西,但是所有其他包都会依赖于types
包。这样,你的store
和services
包都可以导入types
包,而不用担心循环依赖关系。
箭头表示依赖/导入关系
英文:
First of all, this question is slightly subjective because it depends largely on your project and how your project lays out. That being said, here is what I would do if I were you.
Consider adding a types
package. A types
package would rarely be dependent on anything else, but everything would be dependent on the types
package. Then both your store
and services
packages could import the types
package without any concern for cyclical dependencies.
Arrows denote a dependency/import
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论