2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Goで2つのスライスから共通要素を取得したいときはgolang-setをつかおう

Posted at

はじめに

Goで2つのスライスの共通要素を取得する際、愚直にループを回すと以下のようになると思います

package main

import (
	"fmt"
)

func ExampleIntersect() {
	hoge := []string{"a", "b"}
	fuga := []string{"a", "b", "c"}

	var intersection []string
	for _, h := range hoge {
		for _, f := range fuga {
			if h == f {
				intersection = append(intersection, f)
			}
		}
	}

	fmt.Printf("%+v\n", intersection)
	// Output:
	// [a b]
}

Intersect(other Set[T]) Set[T]

golang-setをつかいます

target.Intersect(other)というかたちで、targetスライスとotherスライスの共通要素を取得できます

package main

import (
	"fmt"

	mapset "github.com/deckarep/golang-set/v2"
)

func ExampleIntersect() {
	hoge := mapset.NewSet[string]()
	hoge.Add("a")
	hoge.Add("b")

	fuga := mapset.NewSet[string]()
	fuga.Add("a")
	fuga.Add("b")
	fuga.Add("c")

	fmt.Printf("%+v\n", hoge.Intersect(fuga).ToSlice())
	// Output:
	// [a b]
}

おわり

べんりですね:thumbsup:
著名なOSSでも使用されているのと、コミッターに日本の方もいらしたので愛着湧きました

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?