Go语言中使用整数和字符串数组
时间:2024-03-08
浏览:220
作者:佚名
本篇文章给大家分享《Go语言中使用整数和字符串数组》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。
问题内容
我尝试在 go 中使用数组,但找不到任何可以在同一数组中同时使用整数和字符串的东西。我正在寻找一些可以帮助我解决这个问题的文档。
我让它在 python 中工作,我正在尝试将它翻译成 go。 我在网上找到的大多数信息都显示整数数组或字符串数组,但不是两者组合。
整数和字符串将被传递到另一个函数中,根据整数的值确定哪个字符串将连接到数组的字符串值。
这是一个来自 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] + "."
最终打印输出:
There is one Pie. There are 10 Fish. There are 5 apples.
解决方案
我建议这样做
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)
}
// ...如果您真的只想仅使用数组执行此操作:
list:=[][]interface{}{ {1,"pie"}, {10,"fish"}, {5, "apples"} }
然后,您可以进行类型断言:
intValue:=List[0][0].(int) strValue:=List[0][1].(string)
但是,更好的方法是定义一个包含 int 和 string 成员的结构并使用它的数组。
今天关于《Go语言中使用整数和字符串数组》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
