Go Strings
A string is a piece of text in double quotes. A program can join strings, count their bytes, and compare their text.
Joining text
The + sign joins the two strings into one text. The joined text prints as a single line.
package main
import "fmt"
func main() {
greeting := "Hello, "
name := "Hana"
fmt.Println(greeting + name)
}Counting bytes with len
len counts the bytes in the string. The word hello has five letters, and the count prints as 5.
package main
import "fmt"
func main() {
word := "hello"
fmt.Println(len(word))
}One byte by index
An index reads one byte from a string. Index 1 of hello gives byte 101, the number code for the letter e.
package main
import "fmt"
func main() {
fmt.Println("hello"[1])
}Escapes in a string
The escape \n starts a new line inside the text. The escape \" places a quote mark inside the text.
package main
import "fmt"
func main() {
fmt.Println("One\nTwo")
fmt.Println("She said \"hi\"")
}Comparing text
The == sign compares the variable with a string of the same text. The result prints as true.
package main
import "fmt"
func main() {
word := "go"
fmt.Println(word == "go")
}Example
package main
import "fmt"
func main() {
first := "Hana"
last := "Reyes"
full := first + " " + last
fmt.Println(full)
fmt.Println(len(full))
}Key points
- Use + to join two strings into one longer string.
- len gives the number of bytes in a string.
- An index in square brackets reads one byte from a string.
- The first byte of a string sits at index 0.
- The escape \n in a string starts a new line.
- == compares two strings by their text.
In this example, first holds Hana and last holds Reyes. The + signs join the parts with a space between the names. The program prints the full name, and len counts 10 bytes in it.
Note
len counts bytes, not characters. Plain English text uses one byte per character, so both counts match there.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
What does len("hello") give?