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?
In the Go language, you can set a struct of an array. To do so see the below code example. Where type company struct has a slice of type employee struct. Here, you can see the two different structs, and the employee struct is used as an array in the company struct.
Retrieving the first and last elements in a simple array can most easily be done by using the ARRAY_FIRST and ARRAY_LAST functions. Retrieving the next or previous elements in a simple array can most easily be done by using the ARRAY_PRIOR and ARRAY_NEXT functions.
In the Go slice, you can search an element of string type in the given slice of strings with the help of SearchStrings() function. This function searches for the given element in a sorted slice of strings and returns the index of that element if present in the given slice.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With