Go 주요 주제

Go Runes, Bytes and strings.Builder

Why len("héllo") is 6, how to work with characters, and how to build long strings fast.

  • 중급
  • 4분 분량
  • 실행 가능한 예제 1개
배울 내용
  • Bytes vs runes
  • []rune
  • strings.Builder
héllo
h0
é1-2
l3
l4
o5
5 characters, 6 bytes.

Bytes are not characters

A Go string is a sequence of bytes, and a character outside ASCII takes more than one byte. A rune is one Unicode character. Converting a string to []rune lets you work with characters instead of bytes.

héllo has 5 characters but 6 bytes, because é takes two bytes; that is why the positions printed by range jump from 1 to 3. []rune makes the characters editable. strings.Builder joins many pieces without creating a new string each time.

핵심 포인트

  1. é takes two bytes in UTF-8.
  2. range gives runes, not bytes.
  3. []rune makes characters editable.

실행 가능한 Go 예제

Go
코드 실행 →
main.go
package main

import (
	"fmt"
	"strings"
	"unicode/utf8"
)

func main() {
	word := "héllo"
	fmt.Println(len(word), utf8.RuneCountInString(word))

	parts := []string{}
	for index, r := range word {
		parts = append(parts, fmt.Sprintf("%d:%c", index, r))
	}
	fmt.Println(strings.Join(parts, " "))

	runes := []rune(word)
	runes[1] = 'e'
	fmt.Println(string(runes), len(runes))

	bytes := []byte("Go")
	fmt.Println(bytes, string(bytes[0]))

	var builder strings.Builder
	for i := 3; i > 0; i-- {
		fmt.Fprintf(&builder, "%d...", i)
	}
	builder.WriteString("go!")
	fmt.Println(builder.String())
}
이 예제의 실행 버튼 만들기 코드 실행 결과
6 5
0:h 1:é 3:l 4:l 5:o
hello 5
[71 111] G
3...2...1...go!

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

다음: Anagram Check →

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지