yahuian / blog

📚 blog
1 stars 0 forks source link

Go 函数不要返回一个未导出的类型 #15

Open yahuian opened 8 months ago

yahuian commented 8 months ago
type userModel struct{}

func NewUserModel() *userModel {
    return &userModel{}
}

func (m *userModel) Insert(ctx context.Context, data User) (uint, error) {
    return 0, nil
}

本来的想法是希望调用者仅可以通过 NewUserModel 来实例化,所以将返回值设置为未导出

根据 https://github.com/golang/lint/issues/210 的说法,上层如果想要再次封装的时候,没办法通过

type MyModel struct {
    *userModel
}

此外感觉一个导出的函数返回一个未导出的类型也有一点点怪怪的,所以应该修改为

type UserModel struct{}

func NewUserModel() *UserModel {
    return &UserModel{}
}