Skip to content

Instantly share code, notes, and snippets.

@a13xb
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a13xb/a1bd4c90a0100acfbd19 to your computer and use it in GitHub Desktop.
Save a13xb/a1bd4c90a0100acfbd19 to your computer and use it in GitHub Desktop.
Dilemma: a type can only implement driver.Valuer for value or pointer (not both)
package main
import (
"database/sql"
"database/sql/driver"
_ "github.com/lib/pq"
"log"
)
func E(err error) {
if err != nil {
log.Fatal(err)
}
}
type MyType struct {
S string
}
// Only non-pointer implemented: panic on nil values
// panic: value method main.MyType.Value called using nil *MyType pointer
func (m MyType) Value() (v driver.Value, err error) {
v = m.S
return
}
// Only pointer implemented: error
// error: sql: converting Exec argument #0's type: unsupported type main.MyType, a struct
/*
func (m *MyType) Value() (v driver.Value, err error) {
if m != nil {
v = m.S
}
return
}
*/
func main() {
db, err := sql.Open("postgres", "dbname=homeboy_dev sslmode=disable")
E(err)
exec := func(q string, args ...interface{}) {
_, err = db.Exec(q, args...)
E(err)
}
exec(`drop table if exists t`)
exec(`create table t(i text, j text)`)
i := MyType{"spam"}
var j *MyType // &MyType{"eggs"} // panic if nil
exec(`insert into t(i, j) values($1,$2)`, i, j)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment