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

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.


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