返回一个包含整数和字符串的二维数组的Go函数。

huangapple go评论74阅读模式
英文:

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"})

huangapple
  • 本文由 发表于 2022年3月2日 05:42:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/71314957.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定