英文:
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)
答案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) {}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论