如何解决在两个包之间传递结构体参数时的依赖关系问题?

huangapple go评论92阅读模式
英文:

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
}

以下哪种方式更合理:

  1. User结构体移动到存储器包中(后者可能会有很多不同产品组件的这些结构体)。
  2. User结构体移动到一个单独的公共包中,以便这两个包都可以访问它。
  3. 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

  1. Move User struct into store package (latter might end up a lot of those structs for different product components)
  2. Move User struct into a separate common package so both packages have access to it
  3. Move User struct into a package userstruct under user package

Thank you!

答案1

得分: 1

首先,这个问题有点主观,因为它在很大程度上取决于你的项目以及项目的布局。话虽如此,如果我是你,我会这样做。

考虑添加一个types包。types包很少依赖其他任何东西,但是所有其他包都会依赖于types包。这样,你的storeservices包都可以导入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

如何解决在两个包之间传递结构体参数时的依赖关系问题?

huangapple
  • 本文由 发表于 2021年9月6日 02:25:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/69066179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定