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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!