Logo

Programming-Idioms

History of Idiom 118 > diff from v68 to v69

Edit summary for version 69 by programming-idioms.org:
New Go implementation by user [programming-idioms.org]

Version 68

2022-03-03, 10:06:31

Version 69

2022-08-23, 22:49:28

Idiom #118 List to set

Create the set y from the list x.
x may contain duplicates. y is unordered and has no repeated values.

Turning the list [a,b,c,b] into the set {c,a,b}

Idiom #118 List to set

Create the set y from the list x.
x may contain duplicates. y is unordered and has no repeated values.

Turning the list [a,b,c,b] into the set {c,a,b}
Variables
y,x
Variables
y,x
Code
func sliceToSet[T comparable](x []T) map[T]struct{} {
	y := make(map[T]struct{}, len(x))
	for _, v := range x {
		y[v] = struct{}{}
	}
	return y
}
Comments bubble
sliceToSet is generic. Its type parameter T has a constraint: must be comparable with ==.
Demo URL
https://go.dev/play/p/oM9X2Xxu8Df