더북(TheBook)

Note

슬라이스는 참조 타입이므로 맵의 키로 사용할 수 없다. 하지만 []byte 타입과 []int 32 타입은 string으로 변환하면 맵의 키로 사용할 수 있다.


group1 := []int32{1, 4, 6}
group2 := []int32{2, 4, 5}
group3 := []int32{4, 6, 7}
 
groupMap[group1] = "first"
groupMap[group2] = "second"
groupMap[group3] = "third"

실행 결과

prog.go:14: cannot use group1 (type []int32) as type string in map index
prog.go:15: cannot use group2 (type []int32) as type string in map index
prog.go:16: cannot use group3 (type []int32) as type string in map index

[]int32 타입을 string으로 변환하여 맵의 키로 사용한다.


groupMap := make(map[string]string)
 
group1 := []int32{1, 4, 6}
group2 := []int32{2, 4, 5}
group3 := []int32{4, 6, 7}
 
groupMap[string(group1)] = "first"
groupMap[string(group2)] = "second"
groupMap[string(group3)] = "third"
 
fmt.Println(groupMap[string(group3)]) // third
fmt.Println(groupMap[string(group2)]) // second
fmt.Println(groupMap[string(group1)]) // first

실행 결과

third

second

first

문자열은 유니코드 문자의 코드값을 정수로 표현한 값(rune 또는 int32)의 시퀀스이므로, []int 32 타입을 문자열로 변환할 수 있다. 하지만 문자의 코드값이 올바르지 않다면 문자열 형태로 출력되지 않을 수 있다. 이 코드에서는 단지 실행할 때 []int32 타입 값을 문자열로 인식시켜 맵의 키로 사용했다.

신간 소식 구독하기
뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.