我是golang的新手,并且对此感到困惑.我有一个结构数组:
Users []struct { UserName string Category string Age string }
我想从这个结构数组中检索所有UserName.所以,输出将是类型:
UserList []string
我知道使用循环手动检索元素并从中构造数组的强力方法.有没有其他方法可以做到这一点?
不,循环是要走的路.
这是一个有效的例子.
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) }
不,go不提供python或ruby等许多辅助方法。因此,您必须遍历结构数组并填充数组。