英文:
Copy in array (without size)
问题
我是你的中文翻译助手,以下是翻译好的内容:
我刚开始学习Go语言,我正在尝试从一个数组中提取特定数据(Employee.ID),并将其插入到另一个(新的)数组中。
到目前为止,我还没有成功,我使用的代码如下:
package main
import (
"fmt"
)
type Employee struct {
ID int64
Name string
Department string
}
func main() {
employees := []Employee{{1, "Ram", "India"}, {2, "Criest", "Europe"}}
ids := []int64{}
for i, v := range employees {
fmt.Println(i, v)
}
}
简而言之,我想从employees
数组中提取ID,并将其复制到ids
数组中。employees
数组的大小在任何时候都不是固定的。
感谢你的帮助。
英文:
I am new to go and I'm trying to extract a bit of specific data (Employee.ID) from an array and insert it into another (new) array.
So far I've had no luck in doing so, the code I use is as follows:
package main
import (
"fmt"
)
type Employee struct {
ID int64
Name string
Department string
}
func main() {
employees := []Employee{{1, "Ram", "India"}, {2, "Criest", "Europe"}}
ids := []int64{}
for i, v := range employees {
fmt.Println(i, v)
}
}
In short, I want to extract ID from the employees
array and copy those to the ids
array. The size of employees
array is not fixed at any point in time.
Thanks for all your help.
答案1
得分: 6
你可以使用len(employees)
来获取切片的长度。通常情况下,如果你事先知道大小,使用ids := make([]int64, length)
比使用ids := []int64{}
更好,因为随着切片的增长,它会导致更少的内存分配。
ids := make([]int64, len(employees))
for i, e := range employees {
ids[i] = e.ID
}
或者稍微不同的风格:
ids := make([]int64, 0, len(employees)) // 声明容量,但不指定长度
for _, e := range employees {
ids = append(ids, e.ID)
}
英文:
You can get the length of a slice with len(employees)
. Generally, if you know the size up front, ids := make([]int64, length)
is preferrable to ids := []int64{}
because it will result in fewer allocations as the slice grows.
ids := make([]int64, len(employees))
for i,e := range employees{
ids[i] = e.ID
}
Or a slightly alternate style:
ids := make([]int64, 0, len(employees)) // declare capacity, but not length
for _ , e := range employees{
ids = append(ids, e.ID)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论