Mikulas Dite
Mikulas Dite

Reputation: 7941

Go global variable and short variable definition

In the following snippet

package ...

var Conn *sql.DB // outer Conn

func Init(user, pwd, dbname string, port int) {
    Conn, err := sql.Open("postgres", "... args") // inner Conn
    // ..
}

the inner Conn is a new variable and outer Conn will remain null.

By explicitly defining err and replacing the short variable definition with assignment it seems to properly init the outer Conn variable

    var err error
    Conn, err = sql.Open("postgres", "... args") // inner Conn

Is there a simpler way to specify the inner Conn should not really be a scoped variable but instead the global Conn variable? I'm thinking something like package.Conn, but that's invalid inside the package itself.

Upvotes: 2

Views: 1238

Answers (2)

kwolfe
kwolfe

Reputation: 1683

Nope, that's it. := is just a shortcut to New() (https://golang.org/doc/effective_go.html#allocation_new) variable declaration (var foo int). A more idiomatic approach (and better design in general) is to return the connection and not to use global variables.

func Init(user string, pwd string, dbname string, port int) (*sql.DB, error) {
    // ...
}

Dependency injection is your friend, try not to break scope.

Upvotes: 6

Ben Darnell
Ben Darnell

Reputation: 22154

No, there is no shorthand for this. := always assigns to variables in the current (innermost) scope, creating new variables if necessary. To assign to any variables outside the current scope, you must use = instead of :=, and in the case of multiple-assignment this means that all variables must be pre-declared.

Upvotes: 5

Related Questions