我正在寻找有关清理以下结构的最佳方法的建议.我知道Go没有静态方法,通常最好将功能封装在一个单独的包中.我的结构类型互相引用,因此不能在单独的包中声明因为循环导入.
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
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我想加载用户或付款,我只是扔掉接收器:
var u *User
user := u.Get(585)
Run Code Online (Sandbox Code Playgroud)
我可以命名函数本身,这让我觉得不洁净:
func GetUser(id int) *User {
// Returns the user with the given id
}
func GetPayment(id int) *Payment {
// Returns the payment with the given id
}
Run Code Online (Sandbox Code Playgroud)
我真的希望能够.Get在结构上调用或类似,而无需在函数本身中编写结构的名称.这样做的惯用方法是什么?
Dar*_*tle 28
GetUser()并且GetPayment()让我觉得非常清楚和惯用.我不确定你发现什么是不洁净的.
调用.Get()一个结构来返回另一个结构体是让我觉得非常奇怪,不清楚和单一的结构.
我认为这可能只是坚持使用成语并相信你会习惯它.
jor*_*lli 15
有一个Get功能是完美的; 它不以任何方式是单一的.
func (u *User) Get(id int) *User但是,它应该没有任何意义func (u *User) Get(id int) error.您缺少的一件事是您可以在指针上定义方法接收器,然后在该方法内部取消引用指针以覆盖它指向的内容.
像这样:
// Returns the user with the given id
func (u *User) Get(id int) error {
*u = User{ ... } // dereference the pointer and assign something to it
return nil // or an error here
}
Run Code Online (Sandbox Code Playgroud)
如果有任何问题,请返回错误.现在你可以说
type Getter interface {
Get(int) error
}
Run Code Online (Sandbox Code Playgroud)
因此Get(id)error可以定义任何定义的类型.然后你会像这样使用它:
u := new(User)
if err := u.Get(id); err != nil {
// problem getting user
}
// everything is cool.
Run Code Online (Sandbox Code Playgroud)
Grz*_*ywo 14
Golang不支持构造函数.
请改用工厂功能(Effective Go参考).惯例是使用New前缀:
func NewUser(id int) *User {
// Returns new User instance
}
Run Code Online (Sandbox Code Playgroud)
构造函数和工厂函数之间的区别在于工厂函数不是"附加"到User结构.这是一个正常的函数,碰巧返回,User而Java/C++之类的构造函数是一个修改新创建的User对象的方法.
| 归档时间: |
|
| 查看次数: |
31178 次 |
| 最近记录: |