Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve array of elements from array of structure in golang?

I am new to golang, and got stuck at this. I have an array of structure:

Users []struct {
   UserName string 
   Category string
   Age string
}

I want to retrieve all the UserName from this array of structure. So, output would be of type:

UserList []string 

I know the brute force method of using a loop to retrieve the elements manually and constructing an array from that. Is there any other way to do this?

like image 970
ravi Avatar asked Dec 09 '15 06:12

ravi


People also ask

How do you use an array of structs in Golang?

In the Go language, you can set a struct of an array. To do so see the below code example. Where type company struct has a slice of type employee struct. Here, you can see the two different structs, and the employee struct is used as an array in the company struct.

How can we retrieve an element from an array?

Retrieving the first and last elements in a simple array can most easily be done by using the ARRAY_FIRST and ARRAY_LAST functions. Retrieving the next or previous elements in a simple array can most easily be done by using the ARRAY_PRIOR and ARRAY_NEXT functions.

How do I search a slice?

In the Go slice, you can search an element of string type in the given slice of strings with the help of SearchStrings() function. This function searches for the given element in a sorted slice of strings and returns the index of that element if present in the given slice.


1 Answers

Nope, loops are the way to go.

Here's a working example.

package main

import "fmt"

type User struct {
    UserName string
    Category string
    Age      int
}

type Users []User

func (u Users) NameList() []string {
    var list []string
    for _, user := range u {
        list = append(list, user.UserName)
    }
    return list
}

func main() {
    users := Users{
        User{UserName: "Bryan", Category: "Human", Age: 33},
        User{UserName: "Jane", Category: "Rocker", Age: 25},
        User{UserName: "Nancy", Category: "Mother", Age: 40},
        User{UserName: "Chris", Category: "Dude", Age: 19},
        User{UserName: "Martha", Category: "Cook", Age: 52},
    }

    UserList := users.NameList()

    fmt.Println(UserList)
}
like image 150
openwonk Avatar answered Sep 21 '22 16:09

openwonk