在数组中复制(不包括大小)

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

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

huangapple
  • 本文由 发表于 2017年8月23日 22:28:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/45842551.html
匿名

发表评论

匿名网友

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

确定