如果我有这样的类型,如何使用GORM存储嵌入式结构
type A struct { point GeoPoint } type GeoPoint struct { Lat float64 Lon float64 }
如何才能做到这一点?
我不熟悉Gorm,但是使用sqlx,您需要实现sql.Scanner和sql.Valuer接口,以允许将数据转换为postgres点类型.下面的代码不会检查错误,因此需要进行一些调整.
https://play.golang.org/p/2-Y-wSeAWnj
package main import ( "database/sql/driver" "fmt" "strconv" "strings" ) type GeoPoint struct { Lat float64 Lon float64 } func (gp GeoPoint) Value() (driver.Value,error) { return fmt.Sprintf("(%d,%d)",gp.Lat,gp.Lon),nil } func (gp GeoPoint) Scan(src interface{}) error { raw := src.(string) coords := raw[1 : len(raw)-1] vals := strings.Split(coords,",") gp.Lat,_ = strconv.ParseFloat(vals[0],64) gp.Lon,_ = strconv.ParseFloat(vals[1],64) return nil } func main() { gp := GeoPoint{Lat: 112,Lon: 53} d,_ := gp.Value() fmt.Printf("%+v\n",d) gp.Scan("(53,-110)") fmt.Printf("%+v\n",gp) }