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.
You can declare a string variable like this:
var message string = "Hello, Go!"
Or simply use type inference with := :
greeting := "Welcome to Go strings"
Combine strings using the +
operator:
firstName := "John" lastName := "Doe" fullName := firstName + " " + lastName fmt.Println(fullName) // Output: John Doe
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.
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.
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)
The strings
package provides many useful functions:
strings.ToUpper(str)
β converts to uppercasestrings.ToLower(str)
β converts to lowercasestrings.Contains(str, substr)
β checks substring presencestrings.Replace(str, old, new, n)
β replaces n occurrencesstrings.Split(str, sep)
β splits string into sliceimport "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
strings
package for advanced string manipulation β itβs optimized and idiomatic!
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!