【发布时间】:2013-09-11 18:08:16
【问题描述】:
我正在寻找有关清理以下结构的最佳方法的建议。我知道 Go 没有静态方法,通常是 better to encapsulate functionality in a separate package。我的结构类型相互引用,因此不能在单独的包中声明,因为循环导入。
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
}
我真的希望能够在结构上调用.Get 或类似名称,而无需在函数本身中写入结构的名称。这样做的惯用方法是什么?
【问题讨论】:
标签: go