Golang:为什么 sql.Tx 没有实现 driver.Tx 接口?

huangapple go评论122阅读模式
英文:

Golang: Why sql.Tx does not implement driver.Tx

问题

为什么在下面的示例中编译器会说 sql.Tx 没有实现 driver.Tx,明明 sql.Tx 确实满足接口要求:

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

英文:

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

答案1

得分: 1

你的实现必须完全匹配,所以Store()函数必须接受driver.TX类型,而不仅仅是*sql.Tx类型。

因为sql.Tx实现了driver.Tx接口,所以可以将其作为输入提供。

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) {}
英文:

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) {}

huangapple
  • 本文由 发表于 2021年9月16日 06:23:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/69200383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定