PHpullh

GO · 컬렉션

세트 구현

map[T]struct{}로 세트를 구현합니다. 빈 구조체는 메모리를 차지하지 않습니다.

컬렉션중급setmapstructgenericscollection

핵심 설명

map[T]struct{}로 세트를 구현합니다. 빈 구조체는 메모리를 차지하지 않습니다.

Go code

package main

import "fmt"

type Set[T comparable] map[T]struct{}

func NewSet[T comparable](items ...T) Set[T] {
	s := make(Set[T], len(items))
	for _, item := range items { s[item] = struct{}{} }
	return s
}

func (s Set[T]) Add(item T)    { s[item] = struct{}{} }
func (s Set[T]) Remove(item T) { delete(s, item) }
func (s Set[T]) Has(item T) bool { _, ok := s[item]; return ok }

func (s Set[T]) Union(other Set[T]) Set[T] {
	result := NewSet[T]()
	for k := range s { result.Add(k) }
	for k := range other { result.Add(k) }
	return result
}

func (s Set[T]) Intersect(other Set[T]) Set[T] {
	result := NewSet[T]()
	for k := range s {
		if other.Has(k) { result.Add(k) }
	}
	return result
}

func main() {
	a := NewSet(1, 2, 3, 4)
	b := NewSet(3, 4, 5, 6)

	fmt.Println("합집합:", a.Union(b))       // 1~6
	fmt.Println("교집합:", a.Intersect(b))   // 3, 4
	fmt.Println("Has 2:", a.Has(2))         // true
}

학습 팁

struct{}는 크기가 0바이트입니다. map[T]bool보다 메모리 효율적입니다.

주의할 점

맵의 순회 순서는 랜덤입니다. 세트 출력이 매번 다를 수 있으므로 정렬된 결과가 필요하면 별도로 정렬하세요.

자주 묻는 질문

세트 구현란 무엇인가요?

map[T]struct{} 로 세트를 구현합니다. 빈 구조체는 메모리를 차지하지 않습니다.

세트 구현 학습 시 주의할 점은 무엇인가요?

맵의 순회 순서는 랜덤입니다. 세트 출력이 매번 다를 수 있으므로 정렬된 결과가 필요하면 별도로 정렬하세요.