Home
Go
String Literal Examples
This page was last reviewed on Sep 15, 2024.
Dot Net Perls
String literals. Often 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.
Example. 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.
Part 1 With regular quotes, special sequences like newlines are interpreted as actual newlines.
Part 2 With the backtick character, escape sequences are ignored. The chars are treated as normal values.
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
Paths. The syntax form for string literals that uses the backtick character is ideal for paths on Windows. We can avoid escaping the backslash character.
ReadDir
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
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 15, 2024 (new example).
Home
Changes
© 2007-2024 Sam Allen.