user2490003
user2490003

Reputation: 11890

Returning arbitrary data types in golang

I have a simple golang routine that uses database/sql to open a connection to my Postgres DB and does some stuff

package main

import (
  "fmt"
  "database/sql"
  _ "github.com/lib/pq"
  "log"
)

const (
    DB_USER = "my_user"
    DB_NAME = "my_postgres_db"
)

// The return type here is wrong - what should it be?
func establish_db_connection() sql.DB {
  dbinfo := fmt.Sprintf(
    "user=%s password=%s dbname=%s sslmode=disable", 
    DB_USER, nil, DB_NAME)

  db, err := sql.Open("postgres", dbinfo)
  if err != nil { log.Fatal(err) }

  return db
}

func main() {
  // Get a connection to the DB
  db := establish_db_connection()

  // Do other stuff
  // ...
  // ...
}

I'm having trouble writing the signature for the establish_db_connection function -

func establish_db_connection() sql.DB {

The documentation suggests it returns a sql.DB instance. So should this not be the return type?

I'm super new to golang, so just figuring most of this out for the first time.

Thanks!

Upvotes: 1

Views: 382

Answers (1)

Thundercat
Thundercat

Reputation: 120931

Open returns a *sql.DB, a pointer to a sql.Db. Change the function signature to also return a *sql.DB:

func establish_db_connection() *sql.DB {

Upvotes: 1

Related Questions