douchuitang0331
2015-12-09 06:21
浏览 769
已采纳

如何从Golang中的结构数组中检索元素数组?

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?

图片转代码服务由CSDN问答提供 功能建议

我是golang的新手,因此被困在这里。 我有一个结构数组:

 用户[] struct {
用户名字符串
类别字符串
年龄字符串
} 
   
 
 

我想从此结构数组中检索所有用户名。 因此,输出的类型为:

  UserList [] string 
   
 
 

我知道 使用循环手动检索元素并从中构造一个数组。 还有其他方法吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doude4924 2015-12-09 08:38
    已采纳

    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)
    }
    
    已采纳该答案
    打赏 评论
  • dsapkqaduj6718493 2015-12-09 06:27

    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.

    打赏 评论
  • dthdlv9777 2019-08-23 12:08

    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.

    打赏 评论

相关推荐 更多相似问题