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?
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.
Golang does not support constructors.
Use factory functions instead (Effective Go reference). The convention is to use New
prefix:
func NewUser(id int) *User { // Returns new User instance }
The difference between constructor and factory function is that factory function is not "attached" to the User
struct. It's a normal function that happen to return User
while the Java/C++ like constructor is a method that modifies newly created User
object in place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With