golang-mysql自定义数据类型


本文摘自网络,作者hikerwu,侵删。

自定义数据类型时,需要支持Scan方法和Value方法;

struct slice

type ExampleStruct struct {
    Name  string
    Value string
}

type ExampleStructSlice []ExampleStruct

func (l ExampleStructSlice) Value() (driver.Value, error) {
    bytes, err := json.Marshal(l)
    return string(bytes), err
}

func (l *ExampleStructSlice) Scan(input interface{}) error {
    switch value := input.(type) {
    case string:
        return json.Unmarshal([]byte(value), l)
    case []byte:
        return json.Unmarshal(value, l)
    default:
        return errors.New("not supported")
    }
}

字符串slice

type ExampleStringSlice []string

func (l ExampleStringSlice) Value() (driver.Value, error) {
    bytes, err := json.Marshal(l)
    return string(bytes), err
}

func (l *ExampleStringSlice) Scan(input interface{}) error {
    switch value := input.(type) {
    case string:
        return json.Unmarshal([]byte(value), l)
    case []byte:
        return json.Unmarshal(value, l)
    default:
        return errors.New("not supported")
    }
}

代码参考:github.com/jinzhu/gorm@v1.9.12/scaner_test.go


相关阅读 >>

Go语言函数方法

聊聊dubbo-Go-proxy的route

Golang如何连接ldap

cento8安装Golang及配置

值得推荐的五种自动化代码审查工具

Go 反射解析结构体标签tag

protoc Go插件编写之三 (自定义选项)

Golang使用socket中文乱码解决方法

Go语言中slice作为参数传递时遇到的一些“坑”

Go学习六·集合(map)

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...