duanbin4847 2019-09-11 19:43
浏览 103
已采纳

在Go中使用int和str的数组

I am trying to use an array in Go but I cannot find anything that works with both integers and strings in the same array. I am looking for some documentation that would help me with this problem.

I have it working in Python and I am trying to translate it into Go. Most of the information I found online is showing either arrays of integers or arrays of strings but not both combined.

The integer & string will be passed into another function, depending on the value of the integer determines which string will be concatenated to the string value of the array.

This is an example from Python:

# This is the set arrays
List = [[1, "Pie"], [10, "Fish"], [5, "apples"]]

#This is the code of the function that each array will be passed into
 if list[0] == 1:
        return "There is one " + list[1] + "."
    else:
        return "There are " + str(list[0]) + " " + list[1] + "."

Final Print Output:

There is one Pie.
There are 10 Fish.
There are 5 apples.
  • 写回答

3条回答 默认 最新

  • dsjq62428 2019-09-11 19:55
    关注

    I would recommend going about this like so

    type Foo struct {
      Number int
      Text string
    }
    
      // ...
      array := []Foo{{Number: 1, Text: "pie"}, {Number: 10, Text: "fish"}, {Number: 5, Text: "apples"}}
      if array[0].Number == 1 {
        fmt.Println(array[0].Text)
      }
      // ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)