Go:如何解决作为参数在两个包之间传递的结构的依赖性?
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
谢谢!
首先,这个问题有点主观,因为它在很大程度上取决于您的项目以及您的项目布局。话虽如此,如果我是你,我会这样做。
考虑添加 types
包。 types
包很少会依赖于其他任何东西,但所有东西都会依赖于 types
包。然后你的 store
和 services
包都可以导入 types
包而不用担心循环依赖。
箭头表示 dependency/import
不知道构建这个的最佳实践是什么,所以我没有循环依赖,我有一个 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
谢谢!
首先,这个问题有点主观,因为它在很大程度上取决于您的项目以及您的项目布局。话虽如此,如果我是你,我会这样做。
考虑添加 types
包。 types
包很少会依赖于其他任何东西,但所有东西都会依赖于 types
包。然后你的 store
和 services
包都可以导入 types
包而不用担心循环依赖。
箭头表示 dependency/import