Go String Data Type

Go String Data Type – Complete Guide with Examples
In Go (Golang), the string data type is used to store textual data, such as names, messages, file paths, and JSON content.
Go strings are simple, powerful, Unicode-aware, and immutable, which makes them safe and efficient.
What Is a String in Go?
A string is a sequence of bytes representing text, usually encoded in UTF-8.
Example
- Text data
- UTF-8 support
- Immutable
Declaring String Variables
Using var
Using Short Declaration (:=)
- Clean
- Type inferred automatically
Zero Value of String
If a string is declared but not initialized, its zero value is an empty string ("").
Output
- No
nil - Safe default value
String Immutability (Very Important)
Strings in Go are immutable, meaning you cannot change individual characters.
Invalid
- Strings cannot be modified directly
- Create a new string instead
String Length
Use len() to get the number of bytes, not characters.
- For Unicode strings, length may differ from character count.
String Indexing
You can access bytes using index.
- Indexing gives bytes
- Convert to
stringfor characters
String Concatenation
Using +
Using fmt.Sprintf
- Better for complex formatting
Raw String Literals (Backticks)
Go supports raw strings using backticks `.
- Preserves formatting
- No escape characters
Interpreted String Literals (Double Quotes)
- Supports escape sequences
Common Escape Characters
| Escape | Meaning |
|---|---|
\n | New line |
\t | Tab |
\" | Double quote |
\\ | Backslash |
String Comparison
Strings can be compared using comparison operators.
- Lexicographical comparison
Looping Through a String
Using for with range (Recommended)
- Unicode-safe
- Uses
rune
Strings to Rune / Byte Conversion
Strings to Byte Slice
String to Rune Slice
- Useful for modification
- Required for Unicode handling
String Functions (strings Package)
- Powerful built-in utilities
Common Mistakes
- Trying to modify string characters
- Confusing bytes with characters
- Using
len()for Unicode length - Heavy string concatenation in loops
Best Practices for Strings in Go
- Use
rangefor Unicode strings - Use
strings.Builderfor heavy concatenation - Prefer raw strings for multi-line text
- Understand immutability
- Use standard library functions
Interview Questions: Go String
1. Are strings mutable in Go?
No.
2. Zero value of string?
Empty string ("").
3. Does len() return characters?
No, it returns bytes.
4. What type does range return for strings?rune.
5. Difference between raw and interpreted strings?
Raw strings ignore escape sequences.
Summary
- Strings store text data
- Immutable and UTF-8 encoded
- Zero value is empty string
len()returns bytes- Rich standard library support
Mastering the Go string data type is essential for text processing, APIs, and real-world Go applications
