-1

Why in the following example compiler says sql.Tx does not implement driver.Tx, seeing that sql.Tx does indeed fulfil the interface:

import (
    "database/sql"
    "database/sql/driver"
)


func main() {
    var myDB store = db{}
}

type store interface {
    Store(tx driver.Tx)
}

type db struct {}

func (db) Store(tx *sql.Tx) {}
type Tx interface {
    Commit() error
    Rollback() error
}
./prog.go:9:6: cannot use db{} (type db) as type store in assignment:
    db does not implement store (wrong type for Store method)
        have Store(*sql.Tx)
        want Store(driver.Tx)

https://play.golang.org/p/p3vryYI_dhV

Cae Vecchi
  • 868
  • 1
  • 10
  • 19
  • 1
    Did you fully read the error message? Is there any part of it that you don't understand? (by the way, the error *does not* claim that `sql.Tx` does not implement `driver.Tx`. Even if it does implement it, that doesn't make those types interchangeable in any context except for [assignment](https://golang.org/ref/spec#Assignability)) – Hymns For Disco Sep 15 '21 at 23:42
  • Note that normal application code has no reason to use the driver package directly. The package is only interesting for implementors. – Peter Sep 16 '21 at 05:14
  • I expected that because one interface has an interface parameter, for some reason I thought the implementator having a parameter that implements the interface parameter would work. – Cae Vecchi Sep 16 '21 at 09:33

1 Answers1

1

Your implementation needs to match exactly, so Store() must accept a driver.TX type. Not only a *sql.Tx.

Because sql.Tx implements the driver.Tx interface it can be provided as the input.

import (
    "database/sql"
    "database/sql/driver"
)

func main() {
    var myDB store = db{}
    sqlTx := &sql.Tx{}
    myDB.Store(sqlTx)
}

type store interface {
    Store(tx driver.Tx)
}

type db struct{}

func (db) Store(tx driver.Tx) {}
metalisticpain
  • 2,698
  • 16
  • 26