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

ちょっとおもしろい重複チェック

重複してるアイテムを抽出できる。位置とか取れないし、可読性悪いし、実用性低いけど。

package main

import (
    "fmt"
)

func main() {
    list := []string{
        "foo",
        "bar",
        "baz",
        "foo",
        "bar",
    }
    dups := map[string]bool{}
    for _, item := range list {
        _, dups[item] = dups[item]
    }
    fmt.Printf("%+v", dups)    // map[foo:true bar:true baz:false]
}

https://play.golang.org/p/HqaCcCZijHE

キモは

_, dups[item] = dups[item]

の一行で、mapのキー存在チェックが2つ目のリターンで取得できることに依ってる。

  1. dupsitem がキーとして存在しない
  2. dups[item]false, false が返る
  3. _, dups[item] = false, false となるため itemdups のキーに入る。値は false
  4. もう一度同じ値の item で処理すると、 dups[item]false, true が返る
  5. _, dups[item] = false, true となるため、 dups[item]true になる

Twitterでつぶやくだけつぶやいてたんだけど、「なんか重複チェックについてすげーひらめき昔しなかったけ」となって、
無駄に期待する羽目になった(そしてやっぱり役に立たずがっかりした)のでQiitaにも転載しとく。

Why do not you register as a user and use Qiita more conveniently?
  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
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