A string in Go is a fixed sequence of UTF-8 bytes. The functions that search, split, and reshape them live in the strings package.
The short declaration is what you will write nearly every time. Go reads the type off the literal, so name is a string without you saying the word.
name := "Ada Lovelace"
fmt.Println(name)var names the type up front and starts you at an empty string, which is handy when the real value arrives further down. %q puts quotes around the output so an empty string is something you can see.
var title string
fmt.Printf("%q\n", title)
title = "Countess of Lovelace"
fmt.Println(title)Backticks give you the text exactly as typed. A backslash stays a backslash and a line break stays a line break, which saves a lot of escaping in Windows paths, regexes, and blocks of JSON.
path := `C:\Users\ada\go`
fmt.Println(path)+ joins two strings and hands back a new one. That reads well for a few pieces; once you are joining inside a loop, strings.Builder is the faster shape.
full := "Ada" + " " + "Lovelace"
fmt.Println(full)len counts bytes. Go stores strings as UTF-8, and é takes two of them, so a five-character word measures six.
fmt.Println(len("hello"))
fmt.Println(len("héllo")) // é is two bytesIndexing a string gives you one byte, which prints as a number. Wrap it in string to see the character that byte stands for.
s := "Go"
fmt.Println(s[0])
fmt.Println(string(s[0]))range decodes the UTF-8 for you, handing back each character with the byte index it starts at. The index jumps from 1 to 3 because é occupies two bytes.
for i, r := range "héllo" {
fmt.Printf("%d: %c\n", i, r)
}A string's bytes are fixed for as long as it exists. To change one, slice out the part you are keeping and build a new string around it.
greet := "hello"
// greet[0] = 'H' is a compile error.
upper := "H" + greet[1:]
fmt.Println(upper)The two length lines are the ones worth remembering: same visible width, different byte count.
$ go run strings.go
Ada Lovelace
""
Countess of Lovelace
C:\Users\ada\go
Ada Lovelace
5
6
71
G
0: h
1: é
3: l
4: l
5: o
Hello