自定义数据类型时,需要支持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
有疑问加站长微信联系(非本文作者))