How to retrieve array of elements from array of structure in golang?
Asked Answered
T

4

18

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?

Teaching answered 9/12, 2015 at 6:21 Comment(0)
M
30

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)
}
Mafaldamafeking answered 9/12, 2015 at 8:38 Comment(2)
@kostya, show off... Since question came from someone new to Go, I wanted to be as explicit as possible. (Less possibility for confusion)Mafaldamafeking
it is still part of Go syntax, used fairly often and you have to know about it when you read Go code. It is less explicit but I believe it is worth mentioning, especially to someone who is new to Go.Neman
T
6

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.

Timothytimour answered 9/12, 2015 at 6:27 Comment(0)
V
4

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.

Vallievalliere answered 23/8, 2019 at 12:8 Comment(0)
K
0

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)
}
Kb answered 15/5, 2023 at 5:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.