interface implementing subset not compatible

85 views
Skip to first unread message

Miha Vrhovnik

unread,
Feb 1, 2021, 8:50:58 AM2/1/21
to golang-nuts

I'm trying to put external library under the interface but it seems that this is not possible the way I thought it would be...

My interfaces are as following...

type Beginner interface {
    Begin(ctx context.Context) (Tx, error)
}

type Querier interface {
    Exec(ctx context.Context, sql string, arguments ...interface{}) (commandTag pgconn.CommandTag, err error)
    Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error)
    QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row
}

type Tx interface {
    Commit(ctx context.Context) error
    Rollback(ctx context.Context) error

    Querier
}


Now I have a function....

func NewFoo (b Beginer) {
}


Into that function I want to pass a struct instance with the method that has a following signature. (This function is not under my control).

Begin(ctx context.Context) (pgx.Tx, error)

Now the pgx.Tx has a following signature

type Tx interface {
    Begin(ctx context.Context) (Tx, error)
    Commit(ctx context.Context) error

    Rollback(ctx context.Context) error

    CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error)
    SendBatch(ctx context.Context, b *Batch) BatchResults
    LargeObjects() LargeObjects

    Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error)

    Exec(ctx context.Context, sql string, arguments ...interface{}) (commandTag pgconn.CommandTag, err error)
    Query(ctx context.Context, sql string, args ...interface{}) (Rows, error)
    QueryRow(ctx context.Context, sql string, args ...interface{}) Row

    // Conn returns the underlying *Conn that on which this transaction is executing.
    Conn() *Conn
}


The go is giving me the following error.

cannot use me.DBpgx() (type *pgxpool.Pool) as type db.Beginner in argument to service.NewFoo:
    *pgxpool.Pool does not implement db.Beginner (wrong type for Begin method)
        have Begin(context.Context) (pgx.Tx, error)
        want Begin(context.Context) (db.Tx, error)
       
how come that this is forbidden as my Tx interface is clearly a subset of pgx.Tx

BR,
Miha

Axel Wagner

unread,
Feb 1, 2021, 9:11:36 AM2/1/21
to Miha Vrhovnik, golang-nuts
Hi,

this is answered (to a degree) in the FAQ: https://golang.org/doc/faq#covariant_types


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/9fc0ff89-867a-464b-a955-07a63eec4296n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages