Distinguish raw and interpreted string literals
Distinguish raw and interpreted string literals
An interpreted string uses double quotes and recognizes escape sequences such as \n (newline), \t (tab) and \" (quotation mark). A raw string uses backticks and preserves backslashes literally. Both produce immutable strings; choose the notation that makes the intended bytes clear.
package main
import ( "fmt")
func main() { fmt.Printf("%q %q\n", "a\nb", `a\nb`)}%q prints quoted, escaped representations. The first value contains a newline byte; the second contains a backslash followed by n. They are different values.
Expected output:
"a\nb" "a\\nb"Multiline literals
package main
import ( "fmt")
func main() { s := `firstsecond` fmt.Printf("%q\n", s) fmt.Println(s == "first\nsecond")}Raw literals may span lines; interpreted literals cannot contain an unescaped source newline. Raw literals cannot contain a backtick and discard carriage return characters in the literal. Use interpreted escapes when those bytes are needed.
Expected output:
"first\nsecond"trueTry it locally
Create the path C:\tmp using a raw literal and an interpreted literal; print whether they match.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Strings and Unicode 01: Distinguish raw and interpreted string literals
Check the lesson objective before moving on.
What does a backslash-n in a raw literal represent?
Which form can directly span multiple source lines?