doukong9316 2012-12-02 15:43
浏览 496
已采纳

Go中的配对/元组数据类型

While doing the final exercise of the Tour of Go, I decided I needed a queue of (string, int) pairs. That's easy enough:

type job struct {
    url string
    depth int
}

queue := make(chan job)
queue <- job{url, depth}

But this got me thinking: are there built-in pair/tuple data types in Go? There is support for returning multiple values from a function, but AFAICT, the multiple value tuples produced are not first-class citizens in Go's type system. Is that the case?

As for the "what have you tried" part, the obvious syntax (from a Python programmer's POV)

queue := make(chan (string, int))

didn't work.

  • 写回答

3条回答 默认 最新

  • dtf0925 2012-12-03 15:08
    关注

    There is no tuple type in Go, and you are correct, the multiple values returned by functions do not represent a first-class object.

    Nick's answer shows how you can do something similar that handles arbitrary types using interface{}. (I might have used an array rather than a struct to make it indexable like a tuple, but the key idea is the interface{} type)

    My other answer shows how you can do something similar that avoids creating a type using anonymous structs.

    These techniques have some properties of tuples, but no, they are not tuples.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题