On a previous posts we discussed Runes, Variables and Strings in Go. Today, let's continue our study of Go Strings by learning about raw string literals.
Raw String Literals
Raw string literals are character sequences between back quotes, as in `foo`. Within raw string literals, no escape sequences are processed; the contents are taken literally. For example:
"name": "john"
}`
fmt.Println(s)
Prints:
"name": "john"
}
Particularities of raw string literals
Here are a few particularities of raw string literals:
- within the quotes any character can appear except from back quote (`)
- the value of a raw string literal is the string composed of the uninterpreted (implicitly UTF-8-encoded) characters between the quotes
- the string may contain newlines
- carriage return characters ('\r') are discarded
- no escape sequences are processed; the contents are taken literally
- a raw string literal may spread over several lines in the source code
When to use raw string literals
Due to its preservation of format and disabled escaping nature, raw string literals are convenient in multiple contexts, including:
- writing regular expressions
- HTML templates
- JSON literals
- command usage messages
- XML
- YAML
- and other formats that require preservation of the formatting
Conclusion
On this post we learned a little more about Strings in Go by reviewing raw string literals. Since manipulating Strings is an essential part of a programmer's life, understanding their particularities is important to master the Go programming language.