Golang raw string literals: What is Escape Backtick in Go

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.

Golang escape backtick

To use a backtick(`) character within a string literal in Golang, escape it using a backslash (`\) to create the string literal instead of backticks.

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

Golang raw string literals

Golang raw string literal is a string surrounded by backticks () instead of double quotes (“`).

Raw string literals can span multiple lines and include special characters without escaping them.

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.

package main

import "fmt"

func main() {
  const s = `Michael Jackson
  King of Pop`

  fmt.Println(s)
}

Output

Michael Jackson
King of Pop

Interpreted string literals in Go

To insert escape characters, use the interpreted string literals delimited by double quotes.

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.

package main

import "fmt"

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

Output

"MJ"

That’s it.

Leave a Comment