package custom_type
import (
"database/sql/driver"
"encoding/json"
"fmt"
)
// 泛型切片类型
type TypedSlice[T any] []T
// Value 实现 driver.Valuer 接口(只需实现非指针类型)
func (s TypedSlice[T]) Value() (driver.Value, error) {
if len(s) == 0 {
return "[]", nil
}
return json.Marshal(s)
}
// Scan 实现 sql.Scanner 接口(必须实现指针类型)
func (s *TypedSlice[T]) Scan(value interface{}) error {
if value == nil {
*s = TypedSlice[T]{}
return nil
}
var data []byte
switch v := value.(type) {
case []byte:
data = v
case string:
data = []byte(v)
default:
return fmt.Errorf("unsupported type for Scan: %T", value)
}
return json.Unmarshal(data, s)
}