CodeBlanks Logo Icon CodeBlanks

String and byte

Learn the byte slice behind a string.

Strings and bytes

A Go string is an immutable sequence of bytes. You can't change a character in place; s[0] = 'G' is a compile error. To change it, convert to []byte (or []rune for Turkish letters) and build a new string:

s := "merhaba"
b := []byte(s)
b[0] = 'M'
fmt.Println(string(b))  // Merhaba

s[i] gives a byte, not a string.

Why immutability helps

Because strings are immutable they can be shared safely, and substrings (s[2:5]) point at the same bytes without copying. The cost: s += "x" in a loop allocates a new string every time. When building text from many pieces, use strings.Builder (you'll see it in the concatenation lesson).

Practice Capitalize the first letter

Declare s := "golang". Convert it to []byte, set the first byte to 'G' and print the new string.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    s := "golang"
    b := []byte(s)
    b[0] = 'G'
    fmt.Println(string(b))
}

Expected output

Golang

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>fmt.Println("Go"[0])</code> print?

  • "G"
  • An error
  • 71 (the byte value of G) Correct answer
  • G

Explanation: Indexing returns a byte (uint8); to see it as a letter use string("Go"[0:1]) or %c.

2 Convert to a byte slice

Question
b := []____(s)
b[0] = 'M'
Answer
b := []byte(s)
b[0] = 'M'

Explanation: []byte(s) creates a modifiable byte copy of the string.

3 Expression and type

Term Meaning
"Go" string
"Go"[0] byte (71)
"Go"[0:1] string ("G")
[]byte("Go") [71 111]

All lessons in Beginner