갈루아의 반서재

Strings, bytes, runes and characters in Go


문자열은 단순히 바이트를 나열해놓은 것이다. 문자를 문자열로 저장할 때,  byte-at-a-time representation 을 저장하는 셈이다. 하나의 문자를 가진 문자열 상수를 다음의 3가지 서로 다른 방법으로 출력하는 간단한 프로그램을 만들어보자.

  • plain string
  • ASCII-only quoted string
  • individual bytes in hexadecimal 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main
 
import "fmt"
 
func main() {
    const placeOfInterest = `⌘`
 
    fmt.Printf("plain string: ")
    fmt.Printf("%s", placeOfInterest)
    fmt.Printf("\n")
 
    fmt.Printf("quoted string: ")
    fmt.Printf("%+q", placeOfInterest)
    fmt.Printf("\n")
 
    fmt.Printf("hex bytes: ")
    for i := 0; i < len(placeOfInterest); i++ {
        fmt.Printf("%x ", placeOfInterest[i])
    }
    fmt.Printf("\n")
}
cs

결과는 다음과 같다. 

1
2
3
4
~/go/src/strings# ./strings
plain string: ⌘
quoted string"\u2318"
hex bytes: e2 8c 98
cs

이것이 의미하는 바는 유니코드값 U+2318 을 가지는 "Place of Interest" 라는 심볼은 바이트 e2 8c 98 로 표현되며, 이 바이트들은 헥사데미컬 값 2138 의 UTF-8 인코딩이라는 것이다. 

http://graphemica.com/%E2%8C%98