ravi
ravi

Reputation: 928

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?

Upvotes: 19

Views: 24388

Answers (4)

mugi
mugi

Reputation: 474

Yes you can. Using https://github.com/szmcdull/glinq you can do:

package main

import (
    "fmt"

    "github.com/szmcdull/glinq/garray"
)

func main() {
    var users []struct {
        UserName string
        Category string
        Age      string
    }
    var userNames []string
    userNames = garray.MapI(users, func(i int) string { return users[i].UserName })
    fmt.Printf("%v\r\n", userNames)
}

Upvotes: 1

Nick N.
Nick N.

Reputation: 13578

No, not out of the box.

But, there is a Go package which has a lot of helper methods for this. https://github.com/ahmetb/go-linq

If you import this you could use:

From(users).SelectT(func(u User) string { return u.UserName })

This package is based on C# .NET LINQ, which is perfect for this kind of operations.

Upvotes: 5

openwonk
openwonk

Reputation: 15577

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

Upvotes: 30

Salvador Dali
Salvador Dali

Reputation: 222929

No, go does not provide a lot of helper methods as python or ruby. So you have to iterate over the array of structures and populate your array.

Upvotes: 7

Related Questions