Strings
| String literals | |
| Concatenate and compare | |
| Strings are bytes | |
| strings.Builder |
String literals
Double quoted strings interpret escape sequences such as newline markers, while raw strings in backticks keep every character as written.
Raw strings are handy for file paths, patterns, and multiline templates where backslashes must stay untouched.
package main
import "fmt"
func main() {
a := "line one\nline two"
b := `C:\tools\go\bin`
fmt.Println(a)
fmt.Println(b)
}
Concatenate and compare
The plus operator joins strings, and the double equals operator compares them byte by byte.
Comparison is case sensitive, so normalize the case first when user input may vary.
package main
import "fmt"
func main() {
hello := "Hello, " + "Gopher"
fmt.Println(hello)
fmt.Println(hello == "Hello, Gopher")
fmt.Println(hello == "hello, gopher")
}
go run .
Hello, Gopher
true
false
Strings are bytes
A Go string is a read only sequence of bytes, so len reports the byte count and indexing returns a single byte value.
For text processing, prefer a range loop: it decodes one rune per step and also reports the byte position.
package main
import "fmt"
func main() {
s := "Go!"
fmt.Println(len(s))
for i := 0; i < len(s); i++ {
fmt.Println(i, s[i])
}
}
go run .
3
0 71
1 111
2 33
strings.Builder
Joining many pieces with plus in a loop is slow because every step copies the whole result, so the strings package offers Builder for efficient assembly.
Write each fragment with WriteString and collect the final text once with String.
package main
import (
"fmt"
"strings"
)
func main() {
var b strings.Builder
b.WriteString("Go")
b.WriteString(" is ")
b.WriteString("fast")
fmt.Println(b.String())
}
go run .
Go is fast
Next: Conditions with if
Article author: Arthur Isaev