Golang raw string literals and Interpreted string literals

Golang raw string literals “represent strings without any escape processing”. They are enclosed in backticks (`) and can span multiple lines. Raw string literals allow you to include any characters, including escape sequences (e.g., \n, \t), without processing them as special characters.

Example

package main

func main() {
  multi_str := `This is a raw string literal
                with multiple lines
                and include special characters without having to escape them.`

  print(multi_str)
}

Output

This is a raw string literal
with multiple lines
and include special characters without having to escape them

Backtick strings are analogs of any multiline raw string within Python or else Scala: r””” txt””” or within JavaScript: String raw`yello\u000K!`.

They can be helpful in,

  1. For keeping huge text inside.
  2. For regular expressions, you own many backslashes.
  3. For struct tags, put double quotes within.

Raw string literals are helpful when you need to create strings that contain a lot of special characters or that span multiple lines. They can make your code easier to read and maintain by avoiding the need for many backslashes to escape special characters.

Interpreted string literals in Go

In Go, interpreted string literals are strings enclosed in double quotes (“). They allow you to use escape sequences for special characters, such as newline (\n), tab (\t), double quotes (\”), and backslashes (\\). The escape sequences are processed when the string is created, representing the special characters in the resulting string.

Example

package main

import "fmt"

func main() {
  const s = "\tMichael Jackson\n" +
  "King of Pop"

  fmt.Println(s)
}

Output

     Michael Jackson
King of Pop

Double quote escape in Golang

Use the \” to insert a double quote in an interpreted string literal.

Example

package main

import "fmt"

func main() {
  fmt.Println("\"MJ\"")
}

Output

"MJ"

That’s it.