Go String Data Type

Go (Golang) – String Data Type

The string data type in Go is used to store text (sequence of characters).
Go strings are immutable and UTF-8 encoded, which makes them safe and powerful for modern applications.


1️⃣ Declaring Strings

Using var

var name string = "GoLang"

Type Inference

city := "Delhi"

Empty String

var msg string
fmt.Println(msg) // ""

2️⃣ String Literals

🔹 Interpreted String (Double Quotes)

  • Supports escape sequences

text := "Hello\nGo"

🔹 Raw String (Backticks)

  • No escape sequences

  • Multi-line strings supported

html := <h1>Hello Go</h1>
<p>Welcome</p>


3️⃣ String Immutability

Strings cannot be changed after creation.

❌ Invalid:

str := "Go"
str[0] = 'g' // error

✔ Correct (create new string):

str = "go"

4️⃣ String Length

Use len() to get number of bytes, not characters.

s := "Go"
fmt.Println(len(s)) // 2

⚠ For Unicode characters:

s := "नमस्ते"
fmt.Println(len(s)) // bytes, not chars

5️⃣ Accessing Characters (Bytes & Runes)

Byte Access

s := "Go"
fmt.Println(s[0]) // 71 (ASCII)
fmt.Println(string(s[0])) // G

Rune (Unicode-safe)

for _, ch := range s {
fmt.Println(string(ch))
}

6️⃣ String Concatenation

Using +

a := "Hello"
b := "Go"
fmt.Println(a + " " + b)

Using fmt.Sprintf

msg := fmt.Sprintf("%s %s", a, b)

7️⃣ Common String Functions (strings package)

import "strings"

fmt.Println(strings.ToUpper("go")) // GO
fmt.Println(strings.ToLower("GO")) // go
fmt.Println(strings.Contains("golang", "go")) // true
fmt.Println(strings.Replace("go go", "go", "Go", 1))
fmt.Println(strings.Split("a,b,c", ","))
fmt.Println(strings.TrimSpace(" hi "))


8️⃣ String Comparison

fmt.Println("go" == "go") // true
fmt.Println("a" < "b") // true

9️⃣ Convert String ↔ Number

String to Int

import "strconv"

n, _ := strconv.Atoi("123")

Int to String

s := strconv.Itoa(123)

🔟 Best Practices

✔ Use raw strings for HTML / SQL
✔ Use strings.Builder for heavy concatenation
✔ Use rune loops for Unicode safety
✔ Avoid modifying strings directly


Summary

  • Strings are immutable

  • UTF-8 encoded

  • Two types: interpreted & raw

  • Rich standard library support

You may also like...