douquanzhan0315 2018-01-26 18:01
浏览 172
已采纳

如何声明两个不同数据类型的多维数组

I'm Newbie to Go, I have List of Tuple in python as you see below:

data  = [
    (435347,'cat'),  
    (435347,'feline'),
    (435347,'lion'),
    (6765756,'dog'),
    (6765756,'hound'),
    (6765756,'puppy'),
    (435347,'kitten'),
    (987977,'frog')
    ]

how can i convert data into GO equivalent, I have googled it but everywhere they have specified with the same data-type of multidimensional array like this,

int_list := [4][2]int{{1, 0}, {2, 0}, {3, 0}, {4, 0}}

string_list := make([][]string, 0)

a := [1][2]string{{"lion","dog"}}

help me out..!

Updated:

for Mixed-type Collections of Array:

array := []interface{}{1, "dog", "lion", 12, 45.09, true, false}
  • 写回答

2条回答 默认 最新

  • dongluanan7163 2018-01-26 18:05
    关注

    There are two possible solutions here: actual multidimensional arrays of mixed data types (what you seem to be asking for) and arrays of structs (what you probably want).

    Multidimensional arrays of mixed data-types using interfaces

    If you really want to do multi-dimensional arrays of mixed types, you need to use interfaces:

    interfaceArray := [2][2]interface{}{{1,"dog"},{2,"cat"}}
    fmt.Println(interfaceArray)
    

    Outputs:

    [[1 dog] [2 cat]]

    Interfaces must be handled with care as they can be... anything. This means that there is no enforcement that the first argument is an int and the second is a string. I can just as easily add {"lion", 3} and the compiler will be happy, but your program will crash if it doesn't check the type first.

    You can do type conversions and assertions on interfaces to ensure the correct data types.

    Arrays of structured data

    Putting python tuples in a list does not make it a multi-dimensional array. The closest equivalent in Go would be an array of structs.

    type animal struct {
      id int
      name string
    }
    
    animalList := [2]animal{{1, "cat"}, {2, "dog"}}
    fmt.Println(animalList)
    

    Outputs:

    [{1 cat} {2 dog}]

    In this case, the types are clearly defined, and I cannot store {"lion", 3} in the array.

    final note: [size]type defines an array. []type defines a slice. I'm using arrays here as this is what you mention in your question, but slices would be just as (or probably more) appropriate.

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

报告相同问题?

悬赏问题

  • ¥60 求直线方程 使平面上n个点在直线同侧并且距离总和最小
  • ¥50 java算法,给定试题的难度数量(简单,普通,困难),和试题类型数量(单选,多选,判断),以及题库中各种类型的题有多少道,求能否随机抽题。
  • ¥50 rk3588板端推理
  • ¥250 opencv怎么去掉 数字0中间的斜杠。
  • ¥15 这种情况的伯德图和奈奎斯特曲线怎么分析?
  • ¥250 paddleocr带斜线的0很容易识别成9
  • ¥15 电子档案元素采集(tiff及PDF扫描图片)
  • ¥15 flink-sql-connector-rabbitmq使用
  • ¥15 zynq7015,PCIE读写延时偏大
  • ¥15 使用spss做psm(倾向性评分匹配)遇到问题