Original post

Hi, I’ve really just started using seriously and I’m interested in people’s opinions on best practices/common conventions in variable declarations.

I have the following function which does exactly the same thing as far as I’m aware, but has a different syntax. Is there a preferred style that is more accepted among the go community?

Method 1:

// GetDb connects to the postgres database and returns a pointer to a gorm database object
func GetDb() *gorm.DB {
var db *gorm.DB
var dbURL string
var err error
var parsedURL *dburl.URL
if dbURL = os.Getenv("DATABASE_URL"); dbURL == "" {
dbURL = "postgresql://localhost/mydb?sslmode=disable"
}
if parsedURL, err = dburl.Parse(dbURL); err != nil {
log.Fatal(err)
}
if db, err = gorm.Open("postgres", parsedURL.DSN); err != nil {
log.Fatal(err)
}
return db
}

Method 2:

// GetDb connects to the postgres database and returns a pointer to a gorm database object
func GetDb() *gorm.DB {
dbURL := os.Getenv("DATABASE_URL")
if dbURL == "" {
dbURL = "postgresql://localhost/mydb?sslmode=disable"
}
parsedURL, err := dburl.Parse(dbURL)
if err != nil {
log.Fatal(err)
}
db, err := gorm.Open("postgres", parsedURL.DSN)
if err != nil {
log.Fatal(err)
}
return db
}

From what I’ve seen, method 2 seems to be the more popular in tutorials but I personally find method 1 to be clearer.

submitted by /u/AzMoo
[link] [comments]