How to resolve those golang-ci lint issue

I have written below code to create the dbSession only once
but I am getting below warning from golang ci-lint

once is a global variable (gochecknoglobals)
exported func NewDbSession returns unexported type dbSession, which can be annoying to use (golint)

  var (
    	once   sync.Once
    	dbSess dbSession
    )

     type dbSession struct {
           session *gocql.Session
     }

func NewDbSession() dbSession {
	once.Do(func() {
		if dbSess.session == nil {
			session, err := createSession()
			if err != nil {
				panic(err)
			}
			dbSess = dbSession{session: session}
		}
	})

	return dbSess
}

func  createSession() {
        ....
}

This is supposed to be an idiomatic way of implementing the singleton pattern in golang.

  • Firstly, how do we supposed to implement singleton without a global variable?

  • Secondly, sometimes we don’t want to expose the type with the exported function.
    Is it a hard and fast rule in golang to have an exported return type for an exported function which returns?

You can name the global variable _once which will be find. (see GitHub - leighmcculloch/gochecknoglobals: Check that no globals are present in Go code.)

Why?

  • avoid run time error

  • achieve encapsulation

Proper is to expose the type, such that one can use it to argue and reason about own code, while not exposing it’s internal fields.

1 Like

It didn’t solve the issue.
still i am getting _once is a global variable (gochecknoglobals)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.