dongyuxin5353 2015-09-30 13:46
浏览 498
已采纳

在Golang中基于不同的切片过滤结构的切片

In the example code below, I have a few users in manySimpleUsers that I would like to remove from manyFullUsers based on the Username.

If I do it with a nested couple of for... range loops, there will be many cycles required to filter all of the elements, especially when there are large numbers of elements in both Slices.

What is the best way to achieve this in Go?

package main

import "fmt"

func main() {
    fmt.Println("Hello, playground")

    type FullUser struct {
        UserName  string
        UserEmail string
    }

    manyFullUsers := []FullUser{{"foo", "foo@jawohl.com"},
        {"bar", "bar@jawohl.com"},
        {"baz", "baz@jawohl.com"}}

    type SimpleUser struct {
        UserName string
    }

    manySimpleUsers := []SimpleUser{{"foo"}, {"bar"}}

    fmt.Println(manyFullUsers)
    fmt.Println(manySimpleUsers)
}
  • 写回答

1条回答 默认 最新

  • doulei6778 2015-09-30 13:51
    关注

    Create a map then use it to filter.

    func filterByUserName(fu []FullUser, su []SimpleUser) (out []FullUser) {
        f := make(map[string]struct{}, len(su))
        for _, u := range su {
            f[u.UserName] = struct{}{}
        }
        for _, u := range fu {
            if _, ok := f[u.UserName]; ok {
                out = append(out, u)
            }
        }
        return
    }
    

    <kbd>playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波