GO Tutorial



STRINGS IN GO


Strings in Go

In Go, strings represent sequences of bytes (UTF-8 encoded), typically used to store text. Unlike some other languages, strings in Go are immutable β€” meaning once created, you cannot change their content directly.

Declaring Strings

You can declare a string variable like this:

var message string = "Hello, Go!"

Or simply use type inference with := :

greeting := "Welcome to Go strings"

String Concatenation

Combine strings using the + operator:

firstName := "John"
lastName := "Doe"
fullName := firstName + " " + lastName
fmt.Println(fullName)  // Output: John Doe

String Length

Use the built-in len() function to get the length in bytes:

text := "GoLang"
length := len(text)
fmt.Println(length)  // Output: 6

Note: len counts bytes, not characters. For multibyte Unicode characters, length may differ from actual characters.

Accessing Characters

Strings are indexed by bytes, so you can access individual bytes using brackets:

word := "Go"
fmt.Println(word[0])  // Output: 71 (ASCII code for 'G')
fmt.Println(string(word[0])) // Output: G

Since these are bytes, casting to string converts them to characters for display.

Multiline Strings

Use backticks `...` to create raw string literals that can span multiple lines and keep formatting:

multiline := `Hello,
This is a
multiline string`
fmt.Println(multiline)

Common String Functions

The strings package provides many useful functions:

  • strings.ToUpper(str) – converts to uppercase
  • strings.ToLower(str) – converts to lowercase
  • strings.Contains(str, substr) – checks substring presence
  • strings.Replace(str, old, new, n) – replaces n occurrences
  • strings.Split(str, sep) – splits string into slice
import "strings"

text := "Go is awesome"
fmt.Println(strings.ToUpper(text))             // GO IS AWESOME
fmt.Println(strings.Contains(text, "some"))    // true
fmt.Println(strings.Replace(text, "awesome", "great", 1)) // Go is great
Tip: Always use the strings package for advanced string manipulation β€” it’s optimized and idiomatic!

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review