String
literalsOften programs need to have string
data specified within the programs themselves. This data is usually in the form of string
literals.
With the best syntax, we can make our programs easier to read. Raw string
literals in Go use tick characters. Regular expressions often benefit from raw literals.
Go supports 2 syntaxes for string
literals. For simple strings like "cat" we should prefer the double
-quoted version. Escaped characters are treated in different ways.
package main import "fmt" func main() { // Part 1: the newline sequence is treated as a special value. value1 := "cat\ndog" fmt.Println(value1) // Part 2: the newline sequence is treated as two raw chars. value2 := `cat\ndog` fmt.Println(value2) }cat dog cat\ndog
The syntax form for string
literals that uses the backtick character is ideal for paths on Windows. We can avoid escaping the backslash character.
package main import ( "fmt" "os" ) func main() { // Specify the path with backtick syntax. path := `C:\Windows` // Read the directory. outputDirRead, _ := os.Open(path) outputDirFiles, _ := outputDirRead.ReadDir(0) fmt.Println(len(outputDirFiles)) }108
String
literal syntax can improve a program's readability. With a carefully chosen literal syntax form, programs are easier to read—and this will tend to lead to fewer bugs.