Go:Go Strings, Runes, and the strings Package
Go•Strings & Runes

Go Strings, Runes, and the strings Package

In Go, a string is a read-only slice of bytes. Runes represent single Unicode code points (int32).

Syntax

import "strings" strings.Split(s, ",") strings.Join(slice, "|")

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
runeType AliasAlias for int32 representing a single Unicode code point.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Go locally:

package main

import (
    "fmt"
    "strings"
)

func main() {
    raw := "   [email protected]   "
    clean := strings.TrimSpace(raw)

    fmt.Printf("Clean:    %s\n", clean)
    parts := strings.Split(clean, "@")
    fmt.Printf("Username: %s\n", parts[0])
    fmt.Printf("Domain:   %s\n", parts[1])

    // strings.Builder for high performance concatenation
    var sb strings.Builder
    for i := 1; i <= 3; i++ {
        sb.WriteString(fmt.Sprintf("Node-%d ", i))
    }
    fmt.Printf("Cluster:  %s\n", strings.TrimSpace(sb.String()))
}
Expected Output:
Clean:    [email protected]
Username: developer
Domain:   compilra.dev
Cluster:  Node-1 Node-2 Node-3

How It Works: Step-by-Step

  • Lines 10-14: TrimSpace cleans whitespace; Split separates tokens by delimiter.
  • Lines 17-21: strings.Builder constructs strings efficiently without repeated allocations.

Key Concepts

  • Go strings are immutable byte slices containing UTF-8 encoded text.
  • len(str) returns byte count, NOT character count for non-ASCII strings.
  • Use strings.Builder inside loops to avoid heap churn.

Common Mistake: Assuming len(s) returns the number of characters in a string

len(s) returns byte count. Multi-byte UTF-8 characters like emojis or Cyrillic count as multiple bytes.

❌ Incorrect
len("🚀") // Returns 4 bytes, NOT 1 character!
✅ Correct
utf8.RuneCountInString("🚀") // Returns 1 character

Related Go Tutorials & Compiler

Run and test Go on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Go Online Compiler