Go 언어에서 map은 Hash Table로 구현된다.
var m map[keyType]valueType
keyType
은 불변 자료형이어야 한다.m := make(map[keyType]valueType)
// or
m := map[keyType]valueType{}
value, ok := map[key]
value
: key
가 map에 없으면 값의 자료형의 기본값
을 반환한다.ok
: key
존재 여부를 bool
값으로 반환한다.map[key] = value
key
가 map에 존재해도 value
로 덮어 쓴다.delete(map, key)
key
가 아예 삭제됨len(map)
key
개수 반환func count(s string, codeCount map[rune]int) {
for _, r := range s {
codeCount[r]++;
}
}
a = append(a, ..)
와 같이 포인터를 넘긴다.codeCount := map[rune]int{}
count("가나다나", codeCount)
if !reflect.DeepEqual(map[rune]int{'가':1, '나':2, '다':3}, codeCount) {
// not equal
}
reflect.DeepEqual()
을 활용해야 Hash 값에 의존하지 않고 동등성을 비교할 수 있다.func hasDupeRune(s string) bool {
runeSet := map[rune]struct{}{}
for _, r := range s {
if _, exists := runeSet[r]; exists {
return true
}
runeSet[r] = struct{}{}
}
return false;
}
value
로 빈 구조체 struct{}
를 사용하면 bool
을 사용할 때보다 오버헤드를 줄일 수 있다.key
에 여러 value
매핑 불가하다.