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