Help us understand the problem. What is going on with this article?

GoのSliceの重複をMapを使って削除する

More than 1 year has passed since last update.

GoのSliceの重複をMapを使って削除する

ポイント

  • mapの第二引数は、keyが存在するかどうかの真偽値なのでそれを使う
  • Sliceのある値が存在するかどうかをMapで表し、MapのKeyにSliceの実際の値を入れ、Valueに存在することを表すstruct{}{}を入れる

参考: 急いで学ぶGo lang#7 range・Array・slice・map | Developers.IO

コード

package main

import "fmt"

func main() {
    list := []string{"Go", "Java", "Python", "Go", "Ruby", "Go"}

    m := make(map[string]struct{})

    newList := make([]string, 0)

    for _, element := range list {
        // mapでは、第二引数にその値が入っているかどうかの真偽値が入っている
        if _, ok := m[element]; !ok {
            m[element] = struct{}{}
            newList = append(newList, element)
        }
    }

    fmt.Printf("mapの中身 %#v\n", m)
    fmt.Printf("重複削除後 %#v\n", newList)
}

実行結果

mapの中身 map[string]struct {}{"Go":struct {}{}, "Java":struct {}{}, "Python":struct {}{}, "Ruby":struct {}{}}
重複削除後 []string{"Go", "Java", "Python", "Ruby"}

実際のコードはこちら

参考にさせていただいた記事

急いで学ぶGo lang#7 range・Array・slice・map | Developers.IO

Sekky0905
最近GoとGCPに戻ってきました。 以前は、GAE/Go、AWS、TypeScript、Angular、Vueをやっていました。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした