19

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?

4 Answers 4

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

@kostya, show off... Since question came from someone new to Go, I wanted to be as explicit as possible. (Less possibility for confusion)
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.
7

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.

Comments

5

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.