CodeGym /Cursos /Go SELF /Conversions of []byte and []rune and when they are appr...

Conversions of []byte and []rune and when they are appropriate

Go SELF
Nível 14, Lição 2
Disponível

1. Why do we need []byte and []rune

When a person first learns that a string can be converted into a slice, the feeling appears: “oh, now I can finally change the string by index!”. And Go calmly answers: “you can, but not directly”. Strings in Go are immutable: this helps performance, safety, and your future peace of mind.

Therefore, any “string changes” are done by creating a new string. And to conveniently change the contents, we usually temporarily convert the string into a more suitable form:

  • []byte — when we want to work with bytes (often this is about ASCII characters, tabs, line breaks, protocols, “raw” input/output, binary data).
  • []rune — when we want to work with Unicode characters (that is, “humanly”: letters, including Cyrillic, Chinese ideograms, etc.).

The key reason why this matters is that string indexing s[i] works by bytes and returns a byte (essentially uint8), not a “character”.

2. Data model and copying during conversion

Before writing code, it is useful to build a mental picture. Imagine that a string in Go is a box with bytes, and UTF-8 is the set of rules by which some characters take several bytes.

Conversion diagram

Here is the diagram in Mermaid format:

flowchart LR
    S["string (UTF-8 bytes)"]

    B["[]byte (bytes)"]
    R["[]rune (characters / code points)"]

    S -->|"[]byte(s)"| B
    S -->|"[]rune(s)"| R

    B -->|"string(b)"| S2["string (byte interpretation as UTF-8)"]
    R -->|"string(r)"| S3["string (encoding runes in UTF-8)"]

    note1["Each conversion creates a new value\n(copying data)"]

    S -.-> note1
    B -.-> note1
    R -.-> note1

Important: conversions create new values. This is not a “view” of the same data, but a new slice/string.

Why changing []byte(s) does not change the original string

Beginners often want to think like this: “if I made b := []byte(s), then b seems to point to the string, and if I change b, s will change too”. That is not so.

The correct mental model is this: the conversion creates a new value, and the string remains the same.

package main

import "fmt"

func main() {
	s := "go"
	b := []byte(s)
	b[0] = 'G'

	fmt.Println(s)         // go
	fmt.Println(string(b)) // Go
}

This, by the way, is one of the reasons why strings in Go can be passed around calmly anywhere: they are immutable, and nobody will spoil them “behind your back”.

3. Working with bytes: []byte(s)

If you work with a string as a set of bytes (for example, you want to replace "\t" with a space or remove "\r"), then []byte is your friend. Bytes are convenient to change “in place”: b[i] = ..., you can use append, you can create slices.

Let's start with a micro-diagnostic of types and values. Notice that byte is the range 0..255, that is, essentially uint8.

package main

import "fmt"

func main() {
	s := "Go"
	b := []byte(s)

	fmt.Printf("%T %v\n", b[0], b[0]) // uint8 71
	fmt.Printf("%T %v\n", b[1], b[1]) // uint8 111
}

Here 71 and 111 are byte codes ('G' and 'o' in ASCII). While the string consists of ASCII, everything looks very “intuitive”, but this is a trap: in UTF-8, not all characters fit into one byte.

The pattern of “changing a string” through []byte

The most common practical scenario: a string came from input, it has “technical” characters, and we want to normalize it. Let's take a small step toward our educational mini-application (let's call it textlab for short): it will take a string and make it more neat.

For example, let us replace all tabs "\t" with a single space. This is a byte operation: a tab is one byte, a space is one byte.

package main

import "fmt"

func replaceTabsASCII(s string) string {
	b := []byte(s)

	for i := 0; i < len(b); i++ {
		if b[i] == '\t' {
			b[i] = ' '
		}
	}

	return string(b)
}

func main() {
	fmt.Println(replaceTabsASCII("A\tB\tC")) // A B C
}

What is important to notice here.

First, we did not try to do s[i] = ... — you cannot do that, the string is immutable.

Second, string(b) creates a new string based on the byte slice.

Third, this approach is correct as long as we change exactly “technical” ASCII bytes ("\t", "\n", "\r", space). For Cyrillic letters, doing this is dangerous: there a character may be multi-byte, and “hitting the middle of a character” is very easy.

“Collect bytes” and then do string(b)

Sometimes the input string is large, and you want to assemble a new result from pieces. You can do this with append into []byte. This is still a “manual” style, without special buffers — we will use them later, but for now it is useful to feel the mechanics.

Let textlab add a prefix and suffix to the string:

package main

import "fmt"

func wrapWithBrackets(s string) string {
	var b []byte
	b = append(b, '[')
	b = append(b, s...) // string is expanded into bytes
	b = append(b, ']')
	return string(b)
}

func main() {
	fmt.Println(wrapWithBrackets("go"))  // [go]
	fmt.Println(wrapWithBrackets("mir")) // [mir]
}

There is an important point here: append(b, s...) adds UTF-8 bytes. That is fine, we are not breaking UTF-8, because we add the whole string byte by byte. We are not trying to replace anything “inside” characters.

4. Working with runes: []rune(s)

Why []byte is dangerous for “letters”

A very typical situation: you want to make a string “beautiful” — for example, capitalize the first letter. In English, a byte trick sometimes works, but on real text (Cyrillic, Japanese, emoji) it quickly breaks.

To feel the problem, it is important to remember: character literals in single quotes by default have type rune (this is an alias for int32). And byte is uint8, and large values do not fit there.

Here is an example that shows why “putting Cyrillic into byte” is a bad idea (this code does not compile, and that is normal):

package main

func main() {
	// var x byte = 'M' // not allowed: 'M' does not fit into byte (0..255)
}

So if you need to work with “letters”, you need the rune level.

[]rune(s) and safe work “by characters”

[]rune(s) does an important thing: it takes a UTF-8 string and decodes it into a sequence of “characters” (more precisely, Unicode code points). This greatly simplifies life when you need to take the “first character”, “last character”, “third character”, or replace one character with another without risking breaking UTF-8.

A mini-example: replace the first character with another — specifically as a character, not as a byte.

package main

import "fmt"

func main() {
	s := "mir"
	r := []rune(s)
	r[0] = 'M'
	fmt.Println(string(r)) // Mir
}

Here r[0] is the first rune, that is, the first letter, even if it took 2 bytes in UTF-8.

Pattern for textlab: replace the first character

Let's make a function for our mini-application: “if the string is not empty, replace the first character with the given one”. This is a toy function, but it perfectly reinforces the idea: with text, we work through runes.

package main

import "fmt"

func replaceFirstRune(s string, newFirst rune) string {
	r := []rune(s)
	if len(r) == 0 {
		return s
	}
	r[0] = newFirst
	return string(r)
}

func main() {
	fmt.Println(replaceFirstRune("hello", 'H')) // Hello
	fmt.Println(replaceFirstRune("mir", 'M'))   // Mir
}

Notice the check len(r) == 0. This is not “paranoia”, but ordinary care: an empty string is a completely normal case in a real program.

5. Combining approaches in textlab

Sometimes students try to memorize “in which tasks you need []byte and in which []rune” like a spell. It is much more useful to understand the meaning: you choose the data representation for the operation.

How to choose a representation

What you are doing What is more convenient Why
Removing/replacing "\r", "\n", "\t", spaces at the edges/inside (as bytes) []byte These are control ASCII bytes, easy and safe to touch at the byte level
Adding pieces to a string, assembling a result from fragments []byte (or later special buffers) It is convenient to accumulate bytes and convert to a string once
You want the “first/last character”, letter replacements, working with Cyrillic/Unicode []rune You need characters, not UTF-8 bytes
You want “length in characters” (simplified) []rune or range len(s) gives bytes, not characters

There is no magic here: if the operation is “character-based”, take runes; if it is “technically byte-based”, take bytes.

Mini version of textlab

Now let's put everything together in a small but complete example: the program reads a string (for now directly in the code), replaces tabs with spaces (byte normalization), and then replaces the first character with a given one (character operation). This is a good example of how sometimes both representations are appropriate in one pipeline.

package main

import "fmt"

func replaceTabsASCII(s string) string {
	b := []byte(s)
	for i := 0; i < len(b); i++ {
		if b[i] == '\t' {
			b[i] = ' '
		}
	}
	return string(b)
}

func replaceFirstRune(s string, newFirst rune) string {
	r := []rune(s)
	if len(r) == 0 {
		return s
	}
	r[0] = newFirst
	return string(r)
}

func main() {
	s := "\tmir\tgo"
	s = replaceTabsASCII(s)
	s = replaceFirstRune(s, '>')
	fmt.Println(s) // >mir go
}

Here you can see the “grown-up code” trick: we do not choose “one correct type forever”. We choose the type at each step so that a specific operation is simple and safe.

6. Typical mistakes

Mistake #1: trying to change a string by index (s[i] = ...).
Strings in Go are immutable, and the compiler will not let you do that. The correct path is to create a new value: either through concatenation of substrings, or through []byte/[]rune and then rebuilding back into string.

Mistake #2: using []byte for “character-based” operations on Unicode text.
On ASCII this sometimes accidentally works, and that makes the mistake trickier: it seems like “everything is fine”. But as soon as Cyrillic or any multi-byte character appears, byte indices start cutting the string not by characters, and you may corrupt UTF-8. If you think in terms of “letters”, use []rune.

Mistake #3: expecting that changing b := []byte(s) will change the original string s.
The conversion creates a new value: the string remains the same. Therefore, after changing bytes or runes, you must explicitly build a new string using string(b) or string(r). If you forget this step in code, you will be changing “the wrong thing” and wondering why the result does not change.

Mistake #4: trying to put a non-ASCII character into byte.
byte is uint8 (0..255). Many Unicode characters are greater than 255, so expressions like var x byte = 'M' do not compile. This is not Go being picky, but protection against silent errors. For characters, use rune, which by default has the meaning of int32.

1
Tarefa
Go SELF, nível 14, lição 2
Bloqueado
Decodificador de underscores
Decodificador de underscores
1
Tarefa
Go SELF, nível 14, lição 2
Bloqueado
Moldura angular
Moldura angular
1
Tarefa
Go SELF, nível 14, lição 2
Bloqueado
Primeira runa
Primeira runa
1
Tarefa
Go SELF, nível 14, lição 2
Bloqueado
Espelho de texto
Espelho de texto
Comentários
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION