【问题标题】:In golang, how to embed on custom type?在 golang 中,如何嵌入自定义类型?
【发布时间】:2014-12-30 09:09:13
【问题描述】:

我有自定义类型 Int64ArrayChannelChannelList,例如:

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 以便可以调用ScanValue 方法?我尝试了以下方法:

type ChannelList []Channel {
    Int64Array
}

但我收到语法错误。重要的是确保 ChannelList 项目的类型为 Channel,如果通过嵌入无法做到这一点,我可能会创建独立的函数以供 ChannelListInt64Array 调用。

【问题讨论】:

    标签: go


    【解决方案1】:

    在结构中找到匿名(或嵌入字段)(请参阅struct type),而不是在类型别名(或“type declaration”)中。

    你不能在另一个类型声明中嵌入一个类型声明。

    另外,正如“Go: using a pointer to array”的答案所示,您不应该使用指向切片的指针,而是直接使用切片本身 (passed by value)。

    Wessie 请指出in the comments (ia *Int64Array) Scan() 使用指向切片的指针来改变所述切片引用的底层数组。
    我宁愿返回另一个切片而不是改变现有切片。
    话虽如此,Golang Code Review 确实提到:

    如果接收器是structarrayslice,并且它的任何元素都是指向可能发生变异的东西的指针,则更喜欢指针接收器,因为它会让读者更清楚意图.

    【讨论】:

    • Value 已经正常通过,Scan 需要一个指针,因为它变异带有append 的切片。您的最后一段是错误的,当您看到指向切片的指针时,似乎总是包含它已成为一种习惯。
    • @Wessie 同意(已编辑答案)。 “扫描”这个名字让我感到困惑。我没想到似乎是只读操作 (Scan) 会改变其接收器上的任何内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    相关资源
    最近更新 更多