Last active
August 29, 2015 14:25
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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