我正在寻找关于清理以下 struct 的最佳方法的建议.我知道Go没有静态方法,通常是better to encapsulate functionality in a separate package.我的 struct 类型相互引用,因此由于循环导入,无法在单独的包中声明.
type Payment struct {
User *User
}
type User struct {
Payments *[]Payments
}
func (u *User) Get(id int) *User {
// Returns the user with the given id
}
func (p *Payment) Get(id int) *Payment {
// Returns the payment with the given id
}
但是,如果我想加载用户或付款,我只需扔掉接收器:
var u *User
user := u.Get(585)
我可以将函数本身命名为空间,这给我的感觉是不干净的:
func GetUser(id int) *User {
// Returns the user with the given id
}
func GetPayment(id int) *Payment {
// Returns the payment with the given id
}
我真的希望能够只在 struct 上调用.Get
或类似的函数,而不在函数本身中编写 struct 的名称.做这件事的惯用方式是什么?