英文:
function that returns a 2d array of int and string - Go
问题
所以我正在尝试创建一个返回存储整数值和字符串值的二维数组的函数。显然,我可以像在Python中一样使用普通数组,因为Go使用数据类型。
我已经研究了使用结构体,但我不知道是否漏掉了什么,我已经删除了我的一小段代码大约5次,但没有进展。有人能否指点我正确的方向吗?我感觉我一直在原地踏步...
type user_info struct{
id int
name string
}
new_user := []user_info{{id: 1, name: "Max"}}
这将创建一个实例,但是我如何创建一个单一的数组,以便将新用户附加到其中?
英文:
So I'm trying to create a function that returns a 2D array that stores and integer value and a string value. Obviously i can just use a normal array like i would in python as go uses data types.
I've looked into using a struct but i don't know if I'm missing something or not but I've deleted my small bit of code about 5 times and got nowhere, is anyone able to point me in the right direction please, i feel like I'm getting nowhere...
type user_info struct{
id int
name string
}
new_user := []user_info{{id: 1, name: "Max"}}
This will create one instance but how to i create a single array that i can append the new user to?
答案1
得分: 1
你有多种方法可以添加:
new_user := []user_info{
{id: 1, name: "Max"},
{id: 2, name: "John"},
{id: 3, name: "George"},
}
或者你可以逐个添加项目:
new_user = append(new_user, user_info{id: 4, name: "Sam"})
英文:
you have multiple ways to appned:
new_user := []user_info{
{id: 1, name: "Max"},
{id: 2, name: "John"},
{id: 3, name: "George"},
}
or you can append item by item:
new_user = append(new_user, user_info{id: 4, name: "Sam"})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论