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