go - 在 golang 中,如何嵌入自定义类型?

标签 go

我有自定义类型 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

最佳答案

匿名(或嵌入字段)是在结构中找到的(参见 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 or slice 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/

相关文章:

go - golang中没有这样的文件或目录错误

go - 用golang解析时间:无法解析“-08-23 +

go - 如何运行多个 goroutines 并以相同的运行顺序收集结果

testing - 登录golang测试可以吗?还是不进行登录测试是一种做法?

docker - 如何将 Docker 容器中运行的 Grafana 连接到主机上运行的 Prometheus 数据源(在 Docker for Mac 上)?

go - 如何在 protobuf3 中存储 time.duration

python - 为 python 模块创建 golang 绑定(bind)

closures - 我如何在 Go 中使用 Filepath.Walk?

golang 在两个 uint 值上使用 math.max 的正确方法是什么?

javascript - 在js中设置cookie,无法在golang中读取