0

I have a interface:

type Datastore interface {
    InsertString(str string) error
}

I have PostgreSql implementation of this interface:

type DB struct {
    session *sql.DB
}

 func (db *DB) InsertString(str string) error {
    return nil
}

func NewDB(user, password, dbName string) (*DB, error) {
    dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable",
        user, password, dbName)

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

    err = db.Ping()
    if err != nil {
        log.Println("Cannot ping database")
        return nil, err
    }

    return &DB{db}, nil
}

Now I want to get store and use it in my API handlers.

So, I create Environment structure and try to use it:

type Env struct {
    db *store.Datastore
}

func (env *Env) HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
    // A very simple health check.
}

func main() {
    log.Println("Server staring...")

    db, _ := store.NewDB(USER, PASSWORD, DB_NAME)

    env := Env {
        db: db,
    }

    r := mux.NewRouter()
    r.HandleFunc("/health", env.HealthCheckHandler)

    log.Fatal(http.ListenAndServe("localhost:"+PORT, r))
}

But I have a error:

cannot use db (type *store.DB) as type *store.Datastore in field value: *store.Datastore is pointer to interface, not interface

I know, how to fix this. I can use this structure instead of initial:

type Env struct {
    db store.Datastore
}

But I don't want to copy the data.

Sridhar
  • 2,416
  • 1
  • 26
  • 35
Max
  • 1,803
  • 3
  • 25
  • 39
  • 3
    `db *store.Datastore` - store.Datastore is an interface, so remove the pointer symbol *, you don't need it - interfaces can take values and pointers, https://medium.com/@saiyerram/go-interfaces-pointers-4d1d98d5c9c6 – Allen Hamilton Jun 16 '18 at 14:03

1 Answers1

3

Using

type Env struct {
    db store.Datastore
}

is the correct solution. Because store.Datastore is interface type, it is already pointer and youre not coping any data.

ain
  • 22,394
  • 3
  • 54
  • 74
  • Oh, I did not know about it. It seems. that it is not obvious thing. I have read https://stackoverflow.com/a/27178682/4167563 it for now. Thank you! – Max Jun 16 '18 at 14:07