我有自定义类型 Int64Array
、Channel
和 ChannelList
,例如:
type Int64Array []int64
func (ia *Int64Array) Scan(src interface{}) error {
rawArray := string(src.([]byte))
if rawArray == "{}" {
*ia = []int64{}
} else {
matches := pgArrayPat.FindStringSubmatch(rawArray)
if len(matches) > 1 {
for _, item := range strings.Split(matches[1], ",") {
i, _ := strconv.ParseInt(item, 10, 64)
*ia = append(*ia, i)
}
}
}
return nil
}
func (ia Int64Array) Value() (driver.Value, error) {
var items []string
for _, item := range ia {
items = append(items, strconv.FormatInt(int64(item), 10))
}
return fmt.Sprintf("{%s}", strings.Join(items, ",")), nil
}
type Channel int64
type ChannelList []Channel
如何将 Int64Array
嵌入到 ChannelList
中,以便我可以在其上调用 Scan
和 Value
方法?我尝试了以下方法:
type ChannelList []Channel {
Int64Array
}
但我遇到了语法错误。重要的是确保 ChannelList
项目是 Channel
类型,如果通过嵌入无法做到这一点,我可能会创建独立的函数以供 调用>ChannelList
和 Int64Array
。
最佳答案
匿名(或嵌入字段)是在结构中找到的(参见 struct
type ),而不是在类型别名(或“type declaration ”)中。
您不能将类型声明嵌入到另一个类型声明中。
另外,如“Go: using a pointer to array”的答案所示,您不应该使用 slice 指针,直接使用 slice 本身 (passed by value)。
Wessie请指出in the comments (ia *Int64Array) Scan()
使用指向 slice 的指针来改变该 slice 引用的底层数组。
我宁愿返回另一个 slice 而不是改变现有的 slice 。
也就是说,Golang Code Review确实提到:
If the receiver is a
struct
,array
orslice
and any of its elements is a pointer to something that might be mutating, prefer a pointer receiver, as it will make the intention more clear to the reader.
关于go - 在 golang 中,如何嵌入自定义类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27702469/