Chapter 19: String

String data type.

In beginner tutorials (Tour of Go, W3Schools, freeCodeCamp, GeeksforGeeks, etc.) the string section usually gets quite a bit of attention because:

  • almost every program deals with text
  • strings in Go behave differently from many other languages
  • many newcomers get surprised by immutability, UTF-8, byte vs rune, len() behavior, etc.

Let’s go through everything about strings in Go like we’re sitting together with VS Code open, typing and running examples live.

1. Core Facts About string in Go

Property Explanation Example / Consequence
Type name string predeclared / basic type
Zero value “” (empty string) var s string → s == “” is true
Immutable You cannot change a string after creation s[0] = ‘x’ → compile error
UTF-8 encoded Strings are read-only byte slices containing valid UTF-8 Emoji takes 4 bytes, not 1
len(s) Returns number of bytes, not number of characters / runes len(“హై”) = 6, not 2
Comparable == and != work (byte-by-byte) “hello” == “hello” → true
Concatenation Use + operator “Hello” + ” ” + “World”
Backtick raw literals multi-line — no escaping needed perfect for regex, HTML, JSON

2. Declaration & Basic Examples (Run These!)

Go

Typical output:

text

Notice: the 🇮🇳 emoji takes 8 bytes (4 for 🇮 + 4 for 🇳), so “Hello from Hyderabad! 🇮🇳” = 22 ASCII bytes + 8 emoji bytes = 30 bytes.

3. Most Important Rule: Strings are Immutable

You cannot modify a string in place — any “change” creates a new string.

Go

This is why string concatenation in a loop can be slow if done naively:

Go

4. len() vs Number of Characters (Big Gotcha!)

Go

Output:

text

Rule of thumb:

  • Want byte length (network, files, memory) → len(s)
  • Want character / rune count → len([]rune(s)) or utf8.RuneCountInString(s)

5. Indexing & Slicing (Byte Level!)

Go

Warning: slicing strings at arbitrary byte positions can produce invalid UTF-8 → avoid unless you know it’s safe (pure ASCII).

6. Common Real-World Patterns (2026 style)

Go

7. Your Quick Practice Exercise

Create string_practice.go:

Go

Run it — change the string, add more Telugu/emoji/Hindi, see how len vs rune count behaves.

Questions now?

  • Deep dive on strings.Builder vs + vs bytes.Buffer?
  • UTF-8 decoding / encoding in detail?
  • String ↔ []byte conversion safety?
  • Or ready for rune type next? or composite types (slice/struct)?

Keep typing these examples — strings are everywhere in real Go code and understanding bytes vs runes early saves a lot of pain later. You’re doing fantastic! 💪🇮🇳 Let’s keep going! 🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *