Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between backticks (``) & double quotes ("") in golang?

Tags:

go

What is the difference between backticks (``) & double quotes ("") in golang?

like image 753
samadadi Avatar asked Oct 24 '17 18:10

samadadi


2 Answers

In quotes "" you need to escape new lines, tabs and other characters that do not need to be escaped in backticks ``. If you put a line break in a backtick string, it is interpreted as a '\n' character, see https://golang.org/ref/spec#String_literals

Thus, if you say \n in a backtick string, it will be interpreted as the literal backslash and character n.

a := "\n" // This is one character, a line break. b := `\n` // These are two characters, backslash followed by letter n. 
like image 186
gonutz Avatar answered Sep 18 '22 08:09

gonutz


Backtick strings are analogs of multiline raw string in Python or Scala: r""" text """ or in JavaScript:

String.raw`Hi\u000A!` 

They can:

  1. Span multiple lines.

  2. Ignore special characters.

They are useful:

  1. For putting big text inside.

  2. For regular expressions when you have lots of backslashes.

  3. For struct tags to put double quotes in.

like image 36
Eugene Lisitsky Avatar answered Sep 18 '22 08:09

Eugene Lisitsky