Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

go - "Static" method design

I'm looking for advice on the best way to clean up the following structure. I know Go doesn't have static methods and it's usually better to encapsulate functionality in a separate package. My struct types reference each other, and so cannot be declared in separate packages because of circular imports.

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 
}

But, if I want to load a user or payment, I'm just throwing away the receiver:

var u *User
user := u.Get(585)

I could namespace the functions themselves, which strikes me as unclean:

func GetUser(id int) *User {
    // Returns the user with the given id 
}

func GetPayment(id int) *Payment {
    // Returns the payment with the given id 
}

I would really like to be able to just call .Get or similar on the struct without writing the name of the struct in the function itself. What's the idiomatic way to do this?

question from:https://stackoverflow.com/questions/18678135/static-method-design

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

GetUser() and GetPayment() strike me as perfectly clear and idiomatic. I'm not sure what you find unclean about them.

Calling .Get() on a struct to return another struct is the thing that strikes me as very odd, unclear, and unidiomatic.

I think this might be a case of just sticking with the idiom and trusting that you'll get used to it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...